---
title: "Read WFS Dataset"
output: rmarkdown::html_vignette
vignette: >
  %\VignetteIndexEntry{Read WFS Dataset}
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteEncoding{UTF-8}
---

```{r, include = FALSE}
knitr::opts_chunk$set(
  collapse = TRUE,
  comment = "#>"
)
```

## Read

### Read Metadata

```{r read_metadata}
library(kwb.fisbroker)

dataset_id <- "s_wfs_alkis_bezirk"

berlin_bezirke_metadata <- kwb.fisbroker::read_metadata(
  dataset_id, 
  service_type = "WFS"
)

DT::datatable(berlin_bezirke_metadata)
```

### Read WFS

```{r read_wfs}
berlin_bezirke <- kwb.fisbroker::read_wfs(dataset_id)
str(berlin_bezirke)

DT::datatable(berlin_bezirke)
```

## Plot


### Simple Plot

```{r plot_simple}
### Define Helper Function
plot_bezirke <- function(layer) {
  
  ## fix as name for "geometry" (sf v1.0-7) seems to be renamed to "geom" in 
  ## sf v1.0-8 (or if not might be different on macos)
  sf_geometry_name <- c("geom", "geometry")
  columns <- names(layer)[names(layer) %in% c("namgem", sf_geometry_name)]
  
  plot(layer[,columns])
}

plot_bezirke(berlin_bezirke)
```

### Leaflet Plot

```{r plot_leaflet}
### Plot to check if Berlin boundaries are plotted correctly.
### Set target CRS
crs_target <- 4326

basemap <- berlin_bezirke %>%
  sf::st_transform(crs = crs_target) %>%
  leaflet::leaflet() %>%
  leaflet::addTiles() %>%
  leaflet::addProviderTiles(leaflet::providers$CartoDB.Positron) %>%
  leaflet::addPolygons(stroke = FALSE, 
                       fillColor = rainbow(n = length(berlin_bezirke$namgem)), 
                       fill = TRUE) %>% 
  leaflet::addLegend(
    position = "topright",
    colors = rainbow(n = length(berlin_bezirke$namgem)),
    labels = berlin_bezirke$namgem,
    title = "Berliner Bezirke")

basemap

```
