检测哪个多边形是地图边界中心

问题描述 投票:0回答:2

我想自动检测哪个多边形位于地图的中心。当用户在地图上移动时,它应该动态更新。

目前我找不到一种方法来反向查找哪个多边形上有一些坐标。

我想我可以用shinyjs或javascript模拟一个

input$map_shape_click
,从而获得input$map_shape_click$id,但在我使用这个解决方案之前,我想确保没有其他方法。

这是一个最小的例子

library(leaflet)
library(shiny)

# data source :  https://biogeo.ucdavis.edu/data/gadm3.6/Rsp/gadm36_FRA_2_sp.rds
cities <- readRDS(file = "../gadm36_FRA_2_sf.rds")

ui <- fluidPage(leafletOutput("map"))

server <- function(input, output, session) {
  rv <- reactiveValues()
  
  output$map <- renderLeaflet({
    leaflet() %>%
      addProviderTiles(provider = providers$CartoDB.Positron) %>%
      setView(lng = 1, lat = 45, zoom = 8) %>%
      addPolygons(data = cities,layerId = ~NAME_2,label = ~NAME_2)
  })
  
  observeEvent(input$map_bounds,{
    rv$center <- c(mean(input$map_bounds$north, input$map_bounds$south), mean(input$map_bounds$east, input$map_bounds$west))
    # how can I detect on which polygon the center is ?
  })
}
shinyApp(ui = ui, server = server)
r shiny r-leaflet
2个回答
1
投票
  library(leaflet)
  library(shiny)
  library(sf)
  cities <- readRDS(file = "gadm36_FRA_2_sp.rds") %>%
    st_as_sf()
  ui <- fluidPage(leafletOutput("map"))
  server <- function(input, output, session) {
    rv <- reactiveValues()
    output$map <- renderLeaflet({
      leaflet() %>%
        addProviderTiles(provider = providers$CartoDB.Positron) %>%
        setView(lng = 1, lat = 45, zoom = 8) %>%
        addPolygons(data = cities, layerId = ~NAME_2, label = ~NAME_2)
    })
    observeEvent(input$map_bounds, {
      rv$center <- c(mean(input$map_bounds$north, input$map_bounds$south), mean(input$map_bounds$east,
                                                                                input$map_bounds$west))
      pnt       <- st_point(c(rv$center[2], rv$center[1]))
  
      rslt <- cities[which(st_intersects(pnt, cities, sparse = FALSE)),]$NAME_1
      print(rslt)
    })
  }
  shinyApp(ui = ui, server = server)


0
投票

所以我找到了一种用函数来做到这一点的方法

sf::st_intersects

  observeEvent(input$map_bounds,{
        rv$center <- data.frame(x = mean(c(input$map_bounds$north, input$map_bounds$south)),
                            y = mean(c(input$map_bounds$east, input$map_bounds$west)))


    res <- sf::st_as_sf(rv$center, coords=c("y","x"), crs=st_crs(cities$geometry))
    
    intersection <- as.integer(st_intersects(res, cities$geometry))
    print(if_else(is.na(intersection), '', cities$NAME_2[intersection]))
  })
© www.soinside.com 2019 - 2024. All rights reserved.