You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在R Leaflet地图中实现点击州级行政区跳转指定URL的功能

代码修改核心点

  • 修正字段存储逻辑:win_url仅存储纯目标URL,无需包裹<a>标签,匹配window.open的参数要求
  • 修正onRender事件绑定逻辑:给多边形图层绑定点击事件,正确读取特征属性中的URL并跳转
  • 修正语法错误:原代码中state < -的空格问题,调整为合法的赋值符号<-

完整可运行代码

library(tidyverse)
library(tigris)
library(leaflet)

state <-
    states(
        cb = TRUE
    ) %>% 
    filter(STUSPS %in% c('CA', 'WA', 'MD')) %>% 
    mutate(win_url = 
        case_when(
            STUSPS == 'CA' ~ 'https://shiny.demog.berkeley.edu/alexramiller/kqed-evictions/', 
            STUSPS == 'WA' ~ 'https://evictions.study/washington/maps/summary.html', 
            STUSPS == 'MD' ~ 'https://evictions.study/maryland/report/baltimore.html'))

leaflet(state) %>% 
    addMapPane(name = "polygons", zIndex = 410) %>% 
    addMapPane(name = "maplabels", zIndex = 420) %>% # 高zIndex图层会在上层渲染
    htmlwidgets::onRender('
      function(el, x) {
        var map = this;
        map.on("click", function(e) {
          if (e.layer && e.layer.feature && e.layer.feature.properties.win_url) {
            window.open(e.layer.feature.properties.win_url, "_blank");
          }
        });
      }
    ') %>% 
    addProviderTiles("CartoDB.PositronNoLabels") %>%
    addProviderTiles("CartoDB.PositronOnlyLabels", 
                   options = leafletOptions(pane = "maplabels"),
                   group = "map labels") %>%
    addPolygons(
        fillOpacity = .5, 
        color = "Red", 
        stroke = TRUE, 
        weight = 1, 
        opacity = .5, 
        options = pathOptions(pane = "polygons"),
        highlightOptions = highlightOptions(
                    color = "#ff4a4a", 
                    weight = 5,
                    bringToFront = TRUE
                    )
    ) 

实现效果

效果示意图
点击对应州级行政区后,会自动在新标签页打开对应URL。

内容的提问来源于stack exchange,提问作者Tim

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 06:24:03