在闪亮的地图上一起使用 Leafsync 和 LeafletProxy

如何解决在闪亮的地图上一起使用 Leafsync 和 LeafletProxy

我正在尝试在 shiny 应用上显示两个同步地图,该应用显示基于输入物种和年份的两个不同样本中的物种密度。我使用 leafsync 让它工作,但没有设置为使用传单代理,所以每次我更改输入时,地图都会完全重置(即失去定位和缩放)。我希望能够改变物种和年份而不会失去我在地图上的位置。

我知道我需要使用 leafletProxy 在传单地图顶部添加光栅图像而无需重置,但我不确定如何使用 leafsync(否则,这可能是一项工作mapviewtmap),因为两个同步的地图共享一个名称。这是我尝试过的:

不使用 LeafletProxy 的工作版本:

options("rgdal_show_exportToProj4_warnings"="none") # mute warnings from rgdal because I'm using proj strings
library(shiny)
library(shinyWidgets)
library(leaflet)
library(raster)
library(leafsync)
library(shinydashboard)


set.seed(1)
frog <- data.frame(x=sample(seq(from=-105,to=-95,by=.4),300,replace = T),y = sample(seq(from=35,to=45,replace=T),sample1.2000 = runif(300,min=40,max = 250),sample2.2000 = runif(300,sample1.2001 = runif(300,min=10,max = 220),sample2.2001 = runif(300,sample1.2002 = runif(300,min=0,max = 200),sample2.2002 = runif(300,max = 200)
                   )
toad <- data.frame(x=sample(seq(from=-105,500,sample1.2000 = runif(500,min=100,max = 750),sample2.2000 = runif(500,sample1.2001 = runif(500,min=500,max = 900),sample2.2001 = runif(500,max = 600),sample1.2002 = runif(500,min=300,sample2.2002 = runif(500,min=50,max = 600)
                   )

 ui <- 
   fluidPage(
     fluidRow(
       box(width = 12,box(width=6,radioGroupButtons(
             inputId = "species",label = "Target Species",choiceNames  = list("Frog","Toad"),choiceValues = list("frog","toad"),selected = "frog",justified = TRUE,status="primary"
           ),),sliderInput("year",label = "Year",min = 2000,max = 2002,value = 2000,sep="")
       ),fluidRow( 
           uiOutput('map',height = "150vh") 
     )
   )
 

server <- function(input,output) {
  
  # set limits for color scale,dependent on species
  spp_lim <- eventReactive(input$species,{
    switch(input$species,"frog" = c(0:250),# highest frog density is 250
           "toad" = c(0:1000),# highest toad density is 1000
    )
  })
  
  # create a color palette for the map
  map_pal <- reactiveValues() 
  
  observe({
          map_pal$pal <- colorNumeric(palette = "plasma",spp_lim(),na.color = "transparent",reverse=F)
  })
  
  # make map using renderUI and leafsync
  output$map <- renderUI({


    # pull correct columns for correct species
    map_dat <- get(input$species) %>%
      dplyr::select(x,y,paste0("sample1.",input$year),paste0("sample2.",input$year)
                    ) 
     
    
    # rasterize
    raster_1 <- rasterFromXYZ(map_dat[,c(1,2,3)],crs = "+init=epsg:4326 +proj=longlat +ellps=WGS84 " )
    raster_2 <- rasterFromXYZ(map_dat[,4)],crs = "+init=epsg:4326 +proj=longlat +ellps=WGS84 ")
    
    
    # start leafsync
    sync(
      
      # map 1 -------------
      leaflet( options = leafletOptions(minZoom = 3,maxZoom = 7,zoomControl = TRUE)) %>%
        addProviderTiles("CartoDB.VoyagerNoLabels") %>%
        addRasterImage(raster_1,opacity = 0.7,colors =  map_pal$pal,project=TRUE) %>%
        addLegend(position = "bottomright",pal = map_pal$pal,values = spp_lim(),title = paste0(stringr::str_to_title(input$species)," density"),opacity = 1
                  ) %>%
        addControl("<b>Sample 1</b>",position = "topright"),# map 2 ------------
      leaflet( options = leafletOptions(minZoom = 3,zoomControl = TRUE)) %>%
        addProviderTiles("CartoDB.VoyagerNoLabels") %>%
        addRasterImage(raster_2,opacity = 1
        ) %>%       
        addControl("<b>Sample 2</b>",position = "topright")
    )
    
  }) # end render map
  
}


shinyApp(ui = ui,server = server)

和非工作版本设置为使用leafletProxy:

options("rgdal_show_exportToProj4_warnings"="none") # mute warnings from rgdal because I'm using proj strings
library(shiny)
library(shinyWidgets)
library(leaflet)
library(raster)
library(leafsync)
library(shinydashboard)


set.seed(1)
frog <- data.frame(x=sample(seq(from=-105,max = 200)
)
toad <- data.frame(x=sample(seq(from=-105,max = 600)
)



ui <- 
  fluidPage(
    fluidRow(
      box(width = 12,radioGroupButtons(
                inputId = "species",status="primary"
              ),sep="")
          ),fluidRow( 
      uiOutput('map',height = "150vh") 
    )
  )


server <- function(input,output) {
  
  # set limits for scales,# highest toad density is 1000
    )
  })
  
  # create a color palette for the map
  map_pal <- reactiveValues() 
  
  observe({
    map_pal$pal <- colorNumeric(palette = "plasma",reverse=F)
  })
  
  
  
  
  output$map <- renderUI({

    # add blank leaflet map 
    sync(
      leaflet( options = leafletOptions(minZoom = 3,zoomControl = TRUE)) %>%
        addProviderTiles("CartoDB.VoyagerNoLabels") %>%
        setView(lng = -100,lat = 40,zoom = 5),leaflet( options = leafletOptions(minZoom = 3,zoom = 5) 
      )
    
    
  }) # end render map
  

# observe term for adding rasters
  observe({
    
    
    # get data
    map_dat <- get(input$species) %>%
      dplyr::select(x,input$year)) 
    
    # rasterize
    raster_1 <- rasterFromXYZ(map_dat[,crs = "+init=epsg:4326 +proj=longlat +ellps=WGS84 ")
    
    # set palette and data for raster object
    pal <-   map_pal$pal
    

    # NOTE: this next line needs a name specified,but I don't know how to specify 
    # because "map" is the entire sync object,not the individual maps that are being synced,# so I am not accurately telling Shiny which map to add which raster image to.
    leafletProxy("map") %>%
      clearImages() %>% 
      addRasterImage(raster_1,colors = pal,project=TRUE)
    
    
    leafletProxy("map") %>%
      clearImages() %>% 
      addRasterImage(raster_2,project=TRUE)
    
  })
  
}


shinyApp(ui = ui,server = server)

谢谢!

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-
参考1 参考2 解决方案 # 点击安装源 协议选择 http:// 路径填写 mirrors.aliyun.com/centos/8.3.2011/BaseOS/x86_64/os URL类型 软件库URL 其他路径 # 版本 7 mirrors.aliyun.com/centos/7/os/x86
报错1 [root@slave1 data_mocker]# kafka-console-consumer.sh --bootstrap-server slave1:9092 --topic topic_db [2023-12-19 18:31:12,770] WARN [Consumer clie
错误1 # 重写数据 hive (edu)&gt; insert overwrite table dwd_trade_cart_add_inc &gt; select data.id, &gt; data.user_id, &gt; data.course_id, &gt; date_format(
错误1 hive (edu)&gt; insert into huanhuan values(1,&#39;haoge&#39;); Query ID = root_20240110071417_fe1517ad-3607-41f4-bdcf-d00b98ac443e Total jobs = 1
报错1:执行到如下就不执行了,没有显示Successfully registered new MBean. [root@slave1 bin]# /usr/local/software/flume-1.9.0/bin/flume-ng agent -n a1 -c /usr/local/softwa
虚拟及没有启动任何服务器查看jps会显示jps,如果没有显示任何东西 [root@slave2 ~]# jps 9647 Jps 解决方案 # 进入/tmp查看 [root@slave1 dfs]# cd /tmp [root@slave1 tmp]# ll 总用量 48 drwxr-xr-x. 2
报错1 hive&gt; show databases; OK Failed with exception java.io.IOException:java.lang.RuntimeException: Error in configuring object Time taken: 0.474 se
报错1 [root@localhost ~]# vim -bash: vim: 未找到命令 安装vim yum -y install vim* # 查看是否安装成功 [root@hadoop01 hadoop]# rpm -qa |grep vim vim-X11-7.4.629-8.el7_9.x
修改hadoop配置 vi /usr/local/software/hadoop-2.9.2/etc/hadoop/yarn-site.xml # 添加如下 &lt;configuration&gt; &lt;property&gt; &lt;name&gt;yarn.nodemanager.res