簡體   English   中英

使用Shiny和Leaflet在R中創建帶有標記的交互式webmap

[英]Create interactive webmap with markers in R using Shiny and Leaflet

我正在嘗試在R中創建一個交互式webmap,以使用Shiny和Leaflet顯示位置

該想法是用戶選擇一個輸入並且對應於該輸入的標記(lat / long,其將從相應輸入的數據集中取出)顯示在Leaflet圖中(具有放大/縮小功能)。 任何幫助/建議將不勝感激!

(此處上傳的示例數據文件):

enter code here
Server.R

library(shiny)
library(rpart.plot)
library(leaflet)

shinyServer(
function(input, output) {

output$dtmplot <- renderPlot({
dtmplot <- rpart.plot(dtm, type=4, extra=101)

})
observe({  

output$map <- renderLeaflet( {  
for(j in 1:nrow(df))
{
if(df[j, "col1"]==input$input1) {
map <- leaflet() %>%
addTiles() %>% 
addMarkers(lng=df[j,"Longitude"], lat=df[j,"Latitude)
}
}
})
})
}
)


enter code here

UI.R
library(shiny)
library(leaflet)
shinyUI(
pageWithSidebar(

headerPanel("Sample project"),

sidebarPanel(
plotOutput("dtmplot"),
selectInput("input1", 
label = "label1:",
choices = c(“choice1”,”choice2”),
              selected = " choice1"),
sliderInput("slider","Please select slider input",                min=1,max=100,value=20,step=10) 


  ),


   mainPanel(
   leafletOutput("map")

   )

   ))

下面提供了處理傳單地圖中自定義點的基本代碼。 該代碼利用了小冊子GitHub上提供的官方示例並為最終用戶提供了在地圖上顯示自定義位置的功能。

app.R

library(shiny)
library(leaflet)

r_colors <- rgb(t(col2rgb(colors()) / 255))
names(r_colors) <- colors()

ui <- fluidPage(
    leafletOutput("mymap"),
    p(),
    h1("Added example to add more points here:"),
    p(),
    numericInput("long", label = h3("Longitude:"), value = 11.242828),
    numericInput("lat", label = h3("Latitude:"), value = 30.51470),
    actionButton("recalc", "Show point")

)

server <- function(input, output, session) {

    points <- eventReactive(input$recalc, {
        cbind(input$long, input$lat)
    }, ignoreNULL = FALSE)

    output$mymap <- renderLeaflet({
        leaflet() %>%
            setView(lat = 30, lng = 11, zoom = 4) %>%
            addProviderTiles("Stamen.TonerLite",
                             options = providerTileOptions(noWrap = TRUE)
            ) %>%
            addMarkers(data = points())
    })
}

shinyApp(ui, server)

結果

獲得的地圖如下所示:

地圖

說明

機制非常簡單,可以通過以下步驟進行總結:

  1. 您需要將latlon傳遞到地圖以添加addMarkers 在我的例子中,這是通過原始輸入文件完成的,但它可以通過多種方式完成。
  2. 您必須決定向地圖動態添加標記的邏輯; 在本案例中,這是使用actionButton

旁注

  • 在起草這個答案時,對於應該在地圖上顯示的實際數據沒有明確的說明,我發現在官方示例之后生成所需功能而不是嘗試修改提供的代碼會提供更多信息。
  • 值得注意的是, lat/lon值必須具有正確的格式才能顯示在地圖上。
  • 映射setView使示例更具可呈現性,但在實際解決方案中,應動態生成默認的lat/lon值。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM