gpt4 book ai didi

javascript - 通过 R 向传单多边形添加 'click' 事件

转载 作者:行者123 更新时间:2023-12-05 01:52:47 24 4
gpt4 key购买 nike

如何向传单 map 上绘制的每个多边形添加鼠标“单击”事件?我想这样做,这样我就可以根据来自功能的数据过滤一个单独的小部件(在本例中为 WD21CD)。

leaflet.js map with polygons added

---
output: html_document
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE)

library(tidyverse)
library(htmltools)
library(leaflet)

```
```{r cars, echo=FALSE}

url <- 'https://opendata.arcgis.com/api/v3/datasets/bf9d32b1aa9941af84e6c2bf0c54b1bb_0/downloads/data?format=geojson&spatialRefId=4326'
wardShapes <- sf::st_read(url) %>%
filter(WD21CD >= "E05011175" & WD21CD <= "E05011181")

leaflet(wardShapes,elementId = "bhamMap",
height = 550,# width = 10,
options = leafletOptions(minZoom = 10, maxZoom = 14)) %>%
addTiles() %>%
setView(lng = -1.810, lat = 52.555, zoom = 12) %>%
addPolygons(
weight = 0.5, smoothFactor = 0.5,
opacity = 1.0, fillOpacity = 0.2,
highlightOptions = highlightOptions(color = "white", weight = 2, bringToFront = TRUE),
label = ~as.character(WD21NM),
labelOptions = (interactive = TRUE)
)

```

```{js, class.source = "jsvis1", echo=FALSE}
document.getElementById("bhamMap").addEventListener("click", function(e){
console.log("hello");
});

最佳答案

我们可以使用htmlwidgets::onRenderpass custom JS code传单 htmlwidget。

eachLayer 的帮助下方法我们可以为每个多边形图层添加一个点击功能:

---
title: "leaflet polygons clicks"
output: html_document
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE)

library(tidyverse)
library(htmltools)
library(leaflet)
library(sf)
library(htmlwidgets)

```

```{r cars, echo=FALSE}

url <- 'https://opendata.arcgis.com/api/v3/datasets/bf9d32b1aa9941af84e6c2bf0c54b1bb_0/downloads/data?format=geojson&spatialRefId=4326'
wardShapes <- sf::st_read(url) %>%
filter(WD21CD >= "E05011175" & WD21CD <= "E05011181")

leaflet(wardShapes,elementId = "bhamMap",
height = 550,# width = 10,
options = leafletOptions(minZoom = 10, maxZoom = 14)) %>%
addTiles() %>%
setView(lng = -1.810, lat = 52.555, zoom = 12) %>%
addPolygons(
weight = 0.5, smoothFactor = 0.5,
opacity = 1.0, fillOpacity = 0.2,
highlightOptions = highlightOptions(color = "white", weight = 2, bringToFront = TRUE),
label = ~ as.character(WD21NM),
labelOptions = (interactive = TRUE),
options = pathOptions(title = ~ WD21CD, customdata = ~ WD21NM)
) %>% htmlwidgets::onRender("
function(el, x) {
var map = this;
map.eachLayer(function(layer) {
if(layer instanceof L.Polygon){
layer.on('click', function(e){
alert('You clicked on layer._leaflet_id: ' + layer._leaflet_id + '\\nWD21CD: ' + layer.options.title + '\\ncustomdata: ' + layer.options.customdata);
})
.addTo(map)
}
});
}
")

```

result

关于javascript - 通过 R 向传单多边形添加 'click' 事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71459567/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com