0

I am trying to create a pop up for each country on a leaflet map showing the name of the country and a number. I have though come upon a similar problem in stack exchange here.

country <- c("Austria", "Germany", "Slovakia", "Hungary", "Croatia")
# Wanted only five countries
bounds <- map("world", country, fill = TRUE, plot = FALSE)
bounds$value <- c(300, 4, 8, 1, 8)

# Producing leaflet map
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))

When the map is produced the pop ups are displaying the wrong numbers I then proceeded to check out how bounds$names looks like and I see that the first five names of the countries are the following:

"Austria" "Germany:Usedom" "Germany:Fehmarn" "Germany:Rugen" "Germany:4"

The map itself is still showing popups for the countries I want including Austria, Germany, Hungary, Slovakia, and Croatia but just with the wrong numbers. I don't know why map() produced cities for Germany although the top five countries in country[1:5] are "Austria" "Germany" "Slovakia" "Hungary" "Croatia"

How do stop map() from giving me cities and not all the countries I want. If anyone knows a simpler way of doing this I would be happy to know.

knytt
  • 583
  • 5
  • 15
Nick
  • 369
  • 1
  • 3
  • 18

1 Answers1

2

Add an argument exact = TRUE to the call of maps::map(), this solves the problem.

library(leaflet)

country <- c("Austria", "Germany", "Slovakia", "Hungary", "Croatia")

bounds <- maps::map("world", country, fill = TRUE, plot = FALSE, exact = TRUE)

bounds$value <- c(300, 4, 8, 1, 8)

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))

Also creating the HTML labels separately and checking them before passing them to leaflet might help in finding the problems...

knytt
  • 583
  • 5
  • 15