Add Polygons to R shiny leaflet map

无人久伴 提交于 2019-12-03 07:22:53

问题


How do I add polygons from Global Administrative areas, so they are clickable.

The simple way describe in the docs that I tried is

adm <- getData('GADM', country='UKR', level=1)
leaflet() %>% addTiles() %>% addPolygons(data=adm, weight = 3, fillColor = col)

But imagine I want a leaflet map that will have onClick actions later.

Based on SuperZip, I need to have something similar to

  map <- createLeafletMap(session, "map")
  session$onFlushed(once=TRUE, function() {
     map$addPolygon(...) 
  })

However, there is no addPolygon method and I am confused how will it work for SpartialPolygons.

I also tried converting to geoJSON, similar to https://ropensci.org/blog/2013/10/23/style-geojson-polygon/ or this SO question, but doing

  polys <- fromJSON(<json data file>)
  map <- createLeafletMap(session, "map")
  session$onFlushed(once=TRUE, function() {
    map$geoJson(polys)
  })

Gives me an error

Error in func() : attempt to apply non-function

Is there a way to do it? Or what am I doing wrong?


回答1:


I am not sure I really understand the problem, although I read through the question a couple of times. However the code below seems to work for me, as it can easily be combined with a simple onClick event, like a pop up displaying the name of each adm. unit:

---
title: "Ukraine"
runtime: shiny
output: html_document
---

```{r, echo=FALSE, message=F, warning=F}
library(leaflet)
library(raster)

adm <- getData('GADM', country='UKR', level=1)

popup <- paste0("<strong>Name: </strong>", 
                        adm$NAME_1)

leaflet() %>% 
  addTiles() %>% 
  addPolygons(data=adm, weight = 2, fillColor = "yellow", popup=popup)
```


来源:https://stackoverflow.com/questions/29480795/add-polygons-to-r-shiny-leaflet-map

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!