[GIS] Adding a linestring by st_read in Shiny/Leaflet

leafletlinershiny

I have a large shapefile. For a better perfomance I try to load data with st_read() from sf package. The official documentation states that it should be very easy to integrate the shapefile into Leaflet/Shiny. Nevertheless, it does not work.

Error message: missing value where TRUE/FALSE needed

It works with rgdal, but the performance is not that good. Link

I hope that someone can help me out.

small TestData

library(shiny)
library(leaflet)
library(sf)

shapefile <- st_read("pathToshape")

shinyApp(
  ui <-fluidRow(
    column(8,leafletOutput("map", height="600px"))
  ),

server <- function(input, output, session) {
  output$map <- renderLeaflet({
    leaflet() %>% 
      addTiles() %>% 
      setView(lng=16.357795000076294, lat=48.194883921677935, zoom = 15) %>%
      addPolylines(data=shapefile, layerId = shapefile$id, group = shapefile$zeitver, color="red", weight=3,opacity=1)
  })
})

Best Answer

Your test data is a dead link now, but I had a similar issue trying to plot sf linestrings and polygons in leaflet. The full error was

Error in if (length(nms) != n || any(nms == "")) stop("'options' must be a fully named list, or have no names (NULL)") : 
missing value where TRUE/FALSE needed

I was able to successfully plot my geometries by dropping the Z dimension from the line and polygon with st_zm. Here is an example:

library(sf)
library(leaflet)

# create sf linestring with XYZM dimensions 
badLine <- st_sfc(st_linestring(matrix(1:32, 8)), st_linestring(matrix(1:8, 2)))

# check metadata for badLine
> head(badLine)

Geometry set for 2 features 
    geometry type:  LINESTRING
    dimension:      XYZM
    bbox:           xmin: 1 ymin: 3 xmax: 8 ymax: 16
    epsg (SRID):    NA
    proj4string:    NA
    LINESTRING ZM (1 9 17 25, 2 10 18 26, 3 11 19 2...
    LINESTRING ZM (1 3 5 7, 2 4 6 8)

# attempt map; will fail
> leaflet() %>%
+   addTiles() %>%
+   addPolygons(data = badLine)

Error in if (length(nms) != n || any(nms == "")) stop("'options' must be a fully named list, or have no names (NULL)") : 
  missing value where TRUE/FALSE needed

# try again!

# drop Z and M dimensions from badLine
goodLine <- st_zm(badLine, drop = T, what = "ZM")

# map; will plot successfully!
leaflet() %>%
  addTiles() %>%
  addPolygons(data = goodLine)