单击地图后,ObserveEvent不会打印出图层ID

时间:2018-04-17 14:47:08

标签: r shiny leaflet

我正在尝试通过点击地图获取国家/地区信息,但国家/地区名称或Long / lat未打印出来。

任何人都可以在这个问题上启发我吗?

由于

地图来自Natural Earth。

library(rgdal)
library(shiny)
library(leaflet)

folder="."
country <- readOGR(dsn = folder, layer = "ne_110m_admin_0_countries", encoding="UTF-8")
country <- spTransform(country, CRS("+proj=longlat +ellps=GRS80"))

ui<-fluidPage(
  leafletOutput('mymap')
)

server <- function(input, output, session){
  # RV<-reactiveValues(Clicks=list())
  output$mymap<- renderLeaflet(
    leaflet() %>%
      addProviderTiles("CartoDB.Positron") %>%
      addPolygons(data = country, layerId= ~ADMIN, fillColor = "red", fillOpacity = 1,  color = "black", 
                  stroke = T,  weight = 1  
      )
  )
  observeEvent(input$map_shape_click, {
    p<- input$map_shape_click 
    print(p$id) # click on map, no response
  }) 
}

shinyApp(ui=ui, server=server)

1 个答案:

答案 0 :(得分:1)

您的地图名称是&#34; mymap&#34;而不是&#34; map&#34;。因此,您需要将input$map_shape_click替换为input$mymap_shape_click

library(rgdal)
library(shiny)
library(leaflet)

folder="."
country <- readOGR(dsn = folder, layer = "ne_110m_admin_0_countries", 
encoding="UTF-8")
country <- spTransform(country, CRS("+proj=longlat +ellps=GRS80"))

ui<-fluidPage(
  leafletOutput('mymap')
)

server <- function(input, output, session){
  # RV<-reactiveValues(Clicks=list())
  output$mymap<- renderLeaflet(
    leaflet() %>%
      addProviderTiles("CartoDB.Positron") %>%
      addPolygons(data = country, layerId= ~admin, fillColor = "red", 
fillOpacity = 1,  color = "black", 
                  stroke = T,  weight = 1  
      )
  )
  observeEvent(input$mymap_shape_click, {
    p<- input$mymap_shape_click 
    print(p$id) # click on map, no response
  }) 
}

shinyApp(ui=ui, server=server)