Cannot visualize geojson in R using leaflet package - r

I would like to visualize municipalities in R using Leaflet.
This is my code:
library(leaflet)
library(jsonlite)
geojson <- readLines("https://cartomap.github.io/nl/wgs84/gemeente_2020.geojson", warn = FALSE) %>%
paste(collapse = "\n") %>%
fromJSON(simplifyVector = TRUE)
map <- leaflet() %>%
addTiles() %>%
addGeoJSON(geojson, weight = 1, color = "grey") %>%
setView(5.387740, 52.155499, zoom = 7)
map
Alas it is not working. I don't get an error message, but I don't get a map with municipality borders either. Could somebody please point out to me what I am doing wrong?

The addGeoJSON function is expecting a geojson object but jsolite::fromJSON returns a list. This should work:
library(leaflet)
library(sf)
library(geojsonsf)
url <- "https://cartomap.github.io/nl/wgs84/gemeente_2020.geojson"
sf <- st_read(url)
geojson <- sf_geojson(sf)
map <- leaflet() %>%
addTiles() %>%
addGeoJSON(geojson, weight = 1, color = "grey") %>%
setView(5.387740, 52.155499, zoom = 7)
map

Related

Creating a heatmap on R using leaflet function add_heatmap() or addHeatmap()

I am trying to create a plot with heatmap using plotly add_heatmap() function, but it generates an error message saying Error: Must supply z attribute I referred to this site for addHeatmap() function provided by leaflet.extras package.
The following code only displays dots from addCircles() and outputs a warning message and a map as shown below:
final_df %>%
leaflet() %>%
addTiles() %>%
addCircles(
lng = final_df$long,
lat = final_df$lat,
popup = final_df$station_name
) %>% addHeatmap(lng = final_df$long, lat = final_df$lat, radius=5)
I have tried a different function add_heatmap() from leaflet which does not display any maps and generates an error.
final_df %>%
leaflet() %>%
addTiles() %>%
addCircles(
lng = final_df$long,
lat = final_df$lat,
popup = final_df$station_name
) %>% add_heatmap(lng = final_df$long, lat = final_df$lat)
Anyone faced a similar issue and created a heatmap on R?
Remove addCircles part and try:
library(leaflet.extras)
final_df %>%
leaflet() %>%
addTiles() %>%
addHeatmap(lng = final_df$long, lat = final_df$lat, blur = 40, max = 0.05, radius = 15)

Leaflet map with R shows country completely grey

I am starting to become familiar with leaflet in R although I am experiencing some issues. Data works properly when I am plotting the map with ggplot2. However, I was asked to switch to a more dynamic and interactive map for a shiny dashboard. Here I report the code I performed with the image of the 'grey' results I obtained. I am plotting some Italian provincial data. I retrieved the shape file from the website of the Italian Institute of Statistics (2020, versione generalizzata). Nonetheless, I have uploaded the dataframe and the shape file also on GitHub.
library(dplyr)
library(leaflet)
library(rgdal)
library(sf)
# Import data
load('C:/[...]/data_19.rda') # <--- There are several variables, I selected just one of them
# Import Italy shapefile
ita_map = readOGR('C:/[...]/Limiti01012020_g/ProvCM01012020_g',
'ProvCM01012020_g_WGS84', stringsAsFactors = FALSE)
# Merge
colnames(data_19)[1] = "COD_PROV" # <--- This is the numerical provincial code
ita_map_sf = st_as_sf(ita_map)
ita_map_data <- left_join(ita_map_sf, data_19, by = "COD_PROV")
# Generate map with leaflet
ita_map_data %>%
st_transform(crs = 4326) %>%
leaflet() %>%
addProviderTiles("Esri.WorldGrayCanvas") %>%
setView(lat = 41.8719, lng = 12.5674, zoom = 5) %>%
addPolygons(
fillColor = ita_map_data$unilav_ula,
stroke = FALSE,
smoothFactor = 0.2,
fillOpacity = 0.3
)
Here, instead, the result I am getting from the viewer:
I guess there are some problems in the way I dealt with the polygon data frame. I hope someone could give me some hints. Thank you in advance.
See the R leaflet documentation page for plotting Choropleth Maps:
https://rstudio.github.io/leaflet/choropleths.html
You need to specify a color palette you want to use for the map.
The following code produces the output below.
library(dplyr)
library(leaflet)
library(rgdal)
library(sf)
# Import data
load('C:/[...]/data_19.rda') # <--- There are several variables, I selected just one of them
# Import Italy shapefile
ita_map = readOGR('C:/[...]/Limiti01012020_g/ProvCM01012020_g',
'ProvCM01012020_g_WGS84', stringsAsFactors = FALSE)
# Merge
colnames(data_19)[1] = "COD_PROV" # <--- This is the numerical provincial code
ita_map_sf = st_as_sf(ita_map)
ita_map_sf$COD_PROV <- as.numeric(ita_map_sf$COD_PROV)
ita_map_data <- left_join(ita_map_sf, data_19, by = "COD_PROV")
# Specify Color Palette
pal <- colorQuantile("Blues", domain = ita_map_data$unilav_ula, n=5)
# Generate map with leaflet
ita_map_data %>%
st_transform(crs = 4326) %>%
leaflet() %>%
addProviderTiles("Esri.WorldGrayCanvas") %>%
setView(lat = 41.8719, lng = 12.5674, zoom = 5) %>%
addPolygons(
fillColor = ~pal(unilav_ula),
stroke = FALSE,
smoothFactor = 0.2,
fillOpacity = 0.7,
label=~unilav_ula
)

mapview doesn't show multipolygons of a query from osmdata

I am using the osmdata package to bring the universities of Bogota, some of these are mapped as multipolygons. However the plot comes out empty. Any idea how to fix it?
library(osmdata)
library(mapview)
query <- opq(bbox = "Bogota") %>% add_osm_feature(key = "amenity",value = "university") %>% osmdata_sf()
mapview(query$osm_multipolygons[,c("osm_id","name","amenity")], map.types = "OpenStreetMap")
#mapview(query$osm_polygons[,c("osm_id","name","amenity")], map.types = "OpenStreetMap")
Note: when plotting the points or polygons it works correctly.
The solution is to make a transformation to the object's coordinate system. As it's shown in the following:
library(osmdata)
library(mapview)
library(sf)
query <- opq(bbox = "Bogota") %>%
add_osm_feature(key = "amenity",value = "university") %>%
osmdata_sf()
query <- query$osm_multipolygons[,c("osm_id","name","amenity")] %>%
st_transform(st_crs("+proj=utm +ellps=GRS80 +datum=WGS84")) %>%
st_make_valid()
mapview(query, map.types = "OpenStreetMap")
For more information check the following link. Coordinate Systems in R

leaflet() draws shapefile as giant rectangle

I'm running into a problem with leaflet where it is drawing a giant rectangle instead of the shapes. I'm certain there is some issue with the format of the shapefile, but I can't determine what's going wrong. Plotting the file works fine.
file: https://upload.cat/8c8ade09a3489b47
original file source: http://sites.psu.edu/psucz/data/ (at bottom of page)
require(tidyverse)
require(leaflet)
require(rgdal)
ers_shp <- readOGR("ERS10.shp")
#Doesn't work, produces rectangle:
leaflet() %>% addProviderTiles("CartoDB.Positron") %>% addPolygons(data = ers_shp)
#Works, indicating the data is there.
plot(ers_shp, col="#f2f2f2", fill=TRUE, bg="skyblue", lwd=0.25, mar=rep(0,4), border=0 )
This is because you need to convert the polygons to lat/long before passing them to leaflet:
library(sf)
inv <- sf::st_read("ERS10.rep.shp") %>%
sf::st_transform(4326)
leaflet() %>% addProviderTiles("CartoDB.Positron") %>% addPolygons(data = inv)
OR
library(sp)
inv <- rgdal::readOGR("ERS10.rep.shp") %>%
spTransform(CRS("+proj=longlat +datum=WGS84"))
leaflet() %>% addProviderTiles("CartoDB.Positron") %>% addPolygons(data = inv)

R leaflet: adding polygons from shapefile removes tiles

I have a shapefile of neighborhood areas in NYC (https://nycopendata.socrata.com/City-Government/Neighborhood-Tabulation-Areas/cpf4-rkhq).
When I use use leaflet to overlay these polygons the background tiles are not shown.
This is the code I am using:
library(rgdal)
library(leaflet)
nyc = readOGR("geo_export_da30afd0-e475-44e2-90d2-aca31344ef5e.shp",
layer="geo_export_da30afd0-e475-44e2-90d2-aca31344ef5e")
m = leaflet() %>% fitBounds(lng1 = -74.458921, lat1 = 40.550302,
lng2 = -73.683035, lat2=40.89225)
m %>% addTiles()
m %>% addPolygons(data=nyc)
This is the output:
m %>% addTiles() %>% addPolygons(data = nyc)
should work. %>% does not assign but only pipes contents, therefore needs to be a complete chain.

Resources