问题
I am trying to write a script that would allow people to click on a country then a popup would appear and show the country's name and corresponding value. I have successfully created the map and the boundaries of each country, however when you click on, for example Russia, the popup would show India. Below is a simplified version of the script:
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
The map is generated using the leaflet
package in R. Any solutions or advice would be welcome, I am sure it is a simple error that I am making somewhere.
回答1:
I leave two options for you. If you just want to show the country names as they are in bounds
(e.g., Australia:Melville Island), you need to change popup = countries
to popup = ~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))
If you want to just have the country names as you specified in countries
, you want to manipulate names
using gsub()
, for example. Here I removed all characters from :
to the end for each name.
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))
EXTRA
The OP added one more thing to his question. Here is my idea. If you have two things to show in popups, you can do the following. You add value
to bounds
and create popups.
# 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))
来源:https://stackoverflow.com/questions/49512240/how-to-assign-popup-on-map-polygon-that-corresponds-with-the-country-r-leaflet