Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add Polygons to R shiny leaflet map

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?

like image 350
romants Avatar asked Apr 06 '15 22:04

romants


1 Answers

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)
```
like image 116
maRtin Avatar answered Sep 22 '22 11:09

maRtin