4

我正在尝试编写一个脚本,允许人们单击一个国家/地区,然后会出现一个弹出窗口并显示该国家/地区的名称和相应的值。我已经成功创建了每个国家/地区的地图和边界,但是当您单击时,例如俄罗斯,弹出窗口将显示印度。以下是脚本的简化版本:

library(leaflet)
library(maps)

countries <- c("Australia", "South Africa", "India", "Mexico", "USA", "Russia")

values <- c(1,2,3,4,5,6)

bounds <- map("world", countries, fill = TRUE, plot = FALSE)


map <- leaflet(data) %>%
       addTiles() %>%
       addPolygons(data = bounds, group = "Countries", 
                   color = "red", 
                    weight = 2,
                    popup = paste("Country: ", countries, "<br>", "Value: ", values, "<br>"),
                    fillOpacity = 0.1,
                    highlightOptions = highlightOptions(color = "black", 
                                                        weight = 2,
                                                        bringToFront = TRUE))

map

该地图是使用leafletR 中的包生成的。欢迎任何解决方案或建议,我确信这是我在某处犯的一个简单错误。

4

1 回答 1

2

我给你留下两个选择。如果您只想按原样显示国家/地区名称bounds(例如,澳大利亚:梅尔维尔岛),则需要更改popup = countriespopup = ~names.

map1 <- leaflet() %>%
        addProviderTiles("OpenStreetMap.Mapnik") %>%
        addPolygons(data = bounds, group = "Countries", 
                    color = "red", 
                    weight = 2,
                    popup = ~names,
                    fillOpacity = 0.1,
                    highlightOptions = highlightOptions(color = "black", 
                                                        weight = 2,
                                                        bringToFront = TRUE))

在此处输入图像描述

例如,如果您只想拥有在 中指定的国家/地区名称,则需要使用countries进行操作。在这里,我删除了每个名称的所有字符。namesgsub():

map2 <- leaflet() %>%
        addProviderTiles("OpenStreetMap.Mapnik") %>%
        addPolygons(data = bounds, group = "Countries", 
                    color = "red", 
                    weight = 2,
                    popup = ~gsub(x = names, pattern = ":.*$", replacement = ""),
                    fillOpacity = 0.1,
                    highlightOptions = highlightOptions(color = "black", 
                                                        weight = 2,
                                                        bringToFront = TRUE))

在此处输入图像描述

额外的

OP在他的问题中又添加了一件事。这是我的想法。如果您有两件事要在弹出窗口中显示,您可以执行以下操作。您添加valuebounds创建弹出窗口。

# Add values to bounds. 

set.seed(111)
bounds$value <- sample.int(n = 1000, size = 301, replace = TRUE)

map3 <- leaflet() %>%
        addProviderTiles("OpenStreetMap.Mapnik") %>%
        addPolygons(data = bounds, group = "Countries", 
                    color = "red", 
                    weight = 2,
                    popup = paste("Country: ", bounds$names, "<br>",
                                  "Value: ", bounds$value, "<br>"),
                    fillOpacity = 0.1,
                    highlightOptions = highlightOptions(color = "black", 
                                                        weight = 2,
                                                        bringToFront = TRUE))

在此处输入图像描述

于 2018-03-27T14:15:56.960 回答