嗨,大家好,我已经尝试了几个星期,但我无法完成它.R传单的在线资源也不够.真的需要完成这件事.
请帮忙,非常感谢你.
ui.R - >
library(shiny)
library(ggmap)
library(leaflet)
shinyUI(bootstrapPage(
leafletOutput("map"),
br(),
verbatimTextOutput("out")
)
)
Run Code Online (Sandbox Code Playgroud)
server.R - >
library(shiny)
library(ggmap)
library(leaflet)
shinyServer(function(input, output, session) {
output$map <- renderLeaflet({
p <- input$map_click
if(is.null(p)){
leaflet() %>% setView(lng = -43.1729, lat = -22.9068, zoom = 11) %>%
addTiles(options = providerTileOptions(noWrap = TRUE))
}
else{
address <- revgeocode(c(p$lng,p$lat))
leaflet() %>% setView(lng = p$lng, lat = p$lat, zoom = 16) %>%
addTiles(options = providerTileOptions(noWrap = TRUE)) %>%
addCircles(p$lng, p$lat, weight = 1, radius = 100, color = "black",
fillColor = "orange", popup = address, fillOpacity=0.5, opacity=1)
}
})
output$out <- renderPrint({
validate(need(input$map_click, FALSE))
click <- input$map_click
clat <- click$lat
clng <- click$lng
address <- revgeocode(c(clng,clat))
print(clat)
print(clng)
print(address)
})
})
Run Code Online (Sandbox Code Playgroud)
TL; DR
leafletProxy无一遍渲染一切更新地图.我会通过制作原始地图并使用该leafletProxy功能在用户点击位置时更新地图来完成此操作.Rstudio网站上有一个教程,在那里他们展示了如何做到这一点.它有望保存一些计算,因为每次添加一个圆时都不会重新渲染地图.
我还添加了一些我要考虑的其他内容:将圆形数据放在反应数据集中,并将圆圈保持在一个组中,这样您就可以使用额外的观察者/按钮轻松隐藏/显示它们.
这是一个有效的例子.为了记录,我正在使用github的传单版本(并推荐这个,因为这个包正在积极开发中).你可以得到它devtools::install_github('rstudio/leaflet').至少还有一些我认为不在CRAN上的新功能 - 比如很容易创建自定义标记.
library(shiny)
library(ggmap)
library(leaflet)
ui <- shinyUI(bootstrapPage(
leafletOutput("map")
))
server <- shinyServer(function(input, output, session) {
## One alternative: store circles data?
## I dont actually implement this, but you would do this in the observer as well
dat <- reactiveValues(circs = data.frame(lng=numeric(), lat=numeric()))
## Make your initial map
output$map <- renderLeaflet({
leaflet() %>%
setView(lng = -43.1729, lat = -22.9068, zoom = 11) %>%
addTiles(options = providerTileOptions(noWrap = TRUE))
})
## Observe mouse clicks and add circles
observeEvent(input$map_click, {
## Get the click info like had been doing
click <- input$map_click
clat <- click$lat
clng <- click$lng
address <- revgeocode(c(clng,clat))
## Add the circle to the map proxy
## so you dont need to re-render the whole thing
## I also give the circles a group, "circles", so you can
## then do something like hide all the circles with hideGroup('circles')
leafletProxy('map') %>% # use the proxy to save computation
addCircles(lng=clng, lat=clat, group='circles',
weight=1, radius=100, color='black', fillColor='orange',
popup=address, fillOpacity=0.5, opacity=1)
})
})
shinyApp(ui=ui, server=server)
Run Code Online (Sandbox Code Playgroud)
结果看起来应该是这样的(我已经放大了,添加了一些圆圈并激活了弹出窗口).