【问题标题】:R Leaflet : detect on which polygon is the map bounds centerR Leaflet:检测哪个多边形是地图边界中心
【发布时间】:2020-12-08 09:17:43
【问题描述】:

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

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

我想我可以用 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 leaflet


    【解决方案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)
    
    

    【讨论】:

      【解决方案2】:

      所以我找到了一种方法来使用函数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]))
        })
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-05-12
        • 2017-04-30
        • 1970-01-01
        • 2017-11-13
        • 1970-01-01
        • 2014-01-23
        • 2017-08-27
        相关资源
        最近更新 更多