In R (shiny) I'm using Leaflet. I want to use a geojson file with polygons; each polygon has an id. I also want to use a csv-file with measurements for every id in the geojson. My question is: Do I have to merge these files first before I can use them with leaflet or can I use the data from the csv separately in leaflet? And if I have to merge them first, how do I merge these files and keep the polygons in the result, because if I use the function merge, the result will not be a SpatialPlolygonsDataframe.
library(viridis)
library(geojsonio)
library(leaflet)
setwd('H:/Mijn documenten/R')
Neighborhoods <- geojsonio::geojson_read("Buurten/BuurtGrHTB2017_2.geojson",
what = "sp")
deData <- read.csv(file="Buurten/Gegevens.csv", header=TRUE, sep=";")
MapData <- merge(Neighborhoods,deData,by='BU_CODE')
pal <- colorNumeric("viridis", domain = NULL, reverse=TRUE)
leaflet(MapData) %>%
addTiles() %>%
addPolygons(stroke = FALSE, smoothFactor = 0.3, fillOpacity = 1, fillColor=~pal(ifelse(P_GEHUWD<0,NaN,P_GEHUWD))) %>%
addLegend(pal = pal, values = ~(ifelse(P_GEHUWD<0,NaN,P_GEHUWD)), title="Aantal Inwoners", opacity = 1.0)
I recommend using the sf
-package. It's the latest generation of spatial data manipulation in R and easier to handle.
library(sf)
library(tidyverse)
library(geojsonsf)
Neighborhoods <- geojson_sf('H:/Mijn documenten/R/Buurten/BuurtGrHTB2017_2.geojson')
deData <- read.csv(file='H:/Mijn documenten/R/Buurten/Gegevens.csv', header=TRUE, sep=";")
inner_join(Neighbourhoods, deData, by = 'BU_CODE') -> MapData
or without dplyr
MapData <- merge(Neighbourhoods, deData, by = 'BU_CODE')
From there you are able to do whatever you want with leaflet