R在Shiny中使用带有leafletProxy的地理编码来添加标记和路由

时间:2015-05-19 21:22:14

标签: r shiny leaflet

我想使用新的leafletProxy函数将标记(或圆圈标记)添加到闪亮的传单地图中,以及路线上具有点数的路线,具体取决于滑块...理想情况下,如果点击,我还希望改变路线的颜色。

使用geocode()

中使用ggmap函数获得的纬度和经度来添加标记

以下是我到目前为止的尝试......但它似乎没有起作用...任何建议都将不胜感激......

 # ui.R
library(shiny)
library(shinydashboard)

header <- dashboardHeader(
  title = 'Simple dashbaord'
)
body <- dashboardBody(
  fluidRow(
    column(width=12,
           leafletOutput('outputmap',height = 550)
    )
  )
)
sidebar <- dashboardSidebar(
  sidebarSearchForm(textId = "origin.val",
                    buttonId = "button_click_count",
                    label = "Add marker"),
  sliderInput('num','Number of points:',min=1,max=3000,value=30)
  )


dashboardPage(
  header,
  sidebar,
  body
)

#server.R
require(shiny)
require(leaflet)
library(ggmap)
shinyServer(function(input,output){

  # Run Geocode only when button is clicked
  geocode_origin <- eventReactive(input$button_click_count,{
    geocode(input$origin.val)
  })

  # generate base leaflet map
  output$outputmap <- renderLeaflet({
    map <- leaflet() %>% addTiles()
    map
  })


 observeEvent(input$button_click_count,{
    v <- geocode(input$origin.val)
     leafletProxy('outputmap') %>% addCircleMarkers(lng=v$lon,lat=v$lat)
   })

  eventReactive(input$num, {
     num.points <- input$num
     lon.path <- c(v$lon,v$lon + cumsum(rnorm(num.points)))
     lat.path <- c(v$lat,v$lat + cumsum(rnorm(num.points)))
     renderLeaflet({
       leafletProxy('outputmap') %>% addPolylines(lng=lon.path,lat=lat.path)
     })
   })

    })

1 个答案:

答案 0 :(得分:0)

工作代码

require(shiny)
require(leaflet)
library(ggmap)
shinyServer(function(input,output,session){

  # Run Geocode only when button is clicked
  geocode_origin <- eventReactive(input$button_click_count,{
    geocode(input$origin.val)
  })

  # generate base leaflet map
  output$outputmap <- renderLeaflet({
     map <- leaflet() %>% addTiles()
     map
  })


 observeEvent(input$button_click_count,{
    v <- geocode(input$origin.val)
     leafletProxy('outputmap',session) %>% addCircleMarkers(lng=v$lon,lat=v$lat)
  })

  observeEvent(input$num, {
  num.points <- input$num
  v <- geocode(input$origin.val)
  lon.path <- c(v$lon,v$lon + cumsum(rnorm(num.points)))
  lat.path <- c(v$lat,v$lat + cumsum(rnorm(num.points)))
   leafletProxy('outputmap',session) %>% addPolylines(lng=lon.path,lat=lat.path)
  })

})