问题描述
我想基于缩放级别显示我的标记标签.基于( https://rstudio.github.io/leaflet/shiny.html )我尝试使用"input $ MAPID_zoom".在我的示例中,当缩放级别(mapscale
)低于6时,应显示存储在location_name
中的标签.
I want to display my marker labels based on zoom level.Based on (https://rstudio.github.io/leaflet/shiny.html) I tried to use "input$MAPID_zoom". In my example, labels stored in location_name
should be displayed when zoom level (mapscale
) is lower to 6.
我尝试过的:
library(shiny)
library(leaflet)
# my data
df <- data.frame(
location_name = c('S1', 'S2'),
lng = c(-1.554136, -2.10401),
lat = c(47.218637, 47.218637),
stringsAsFactors = FALSE)
# UI
ui <- shinyUI(fluidPage(
leafletOutput('map')
))
# server
server <- shinyServer(function(input, output, session) {
mapscale <- observe({
input$map_zoom # get zoom level
})
output$map <- renderLeaflet({
leaflet() %>%
addTiles() %>%
addMarkers(data=df, lng = ~lng, lat = ~lat,
label =~if(mapscale<6, location_name))
})
})
shinyApp(ui = ui, server = server)
推荐答案
如果您愿意,可以在代码中添加一些说明.如果将缩放包装为反应式功能,请像mapscale()
一样引用它.在R中使用普通的if
语句,在变量前使用~
.那你应该没事的.
A few remarks on your code if you like.If you wrap the zoom in a reactive function, reference it like mapscale()
. Use the normal if
statement in R and the ~
in front of the variable. Then you should be fine.
可复制的示例:
library(shiny)
library(leaflet)
df <- data.frame(
location_name = c('S1', 'S2'),
lng = c(-1.554136, -2.10401),
lat = c(47.218637, 47.218637),
stringsAsFactors = FALSE
)
ui <- shinyUI(
fluidPage(
leafletOutput(outputId = 'map')
)
)
server <- shinyServer(function(input, output, session) {
output$map <- renderLeaflet({
leaflet() %>%
addTiles()
})
observeEvent(
eventExpr = input$map_zoom, {
print(input$map_zoom) # Display zoom level in the console
leafletProxy(
mapId = "map",
session = session
) %>%
clearMarkers() %>%
addMarkers(
data = df,
lng = ~lng,
lat = ~lat,
label = if(input$map_zoom < 6) ~location_name
)
}
)
})
shinyApp(
ui = ui,
server = server
)
这篇关于基于缩放级别的闪亮传单显示标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!