I am trying to display several zipcodes (thus polygons...) on a leaflet map. Data is available as a geojson file here. I chose as an example some zip codes from Seattle.
I tried the following (reproducible example):
library(jsonlite)
library(leaflet)
url <- "https://raw.githubusercontent.com/openseattle/seattle-boundaries/master/data/zip-codes.geojson"
geojson <- fromJSON(url)
map <- leaflet() %>% addTiles() %>% addGeoJSON(geojson)
map
I could not figure out how to properly set addGeoJSON parameters, and calling map only displays the leaflet() %>% addTiles() part...
Documentation is too light for the non json advanced user that I am:
geojson: a GeoJSON list, or character vector of length 1
How should I proceed? Thank you very much in advance for your views on this issue
Regards
You just needed to not parse the geojson to a data.frame, fromJSON(url, FALSE)
library(jsonlite)
library(leaflet)
url <- "https://raw.githubusercontent.com/openseattle/seattle-boundaries/master/data/zip-codes.geojson"
geojson <- fromJSON(url, simplifyVector = FALSE)
leaflet() %>%
addTiles() %>%
addGeoJSON(geojson) %>%
setView(lng = -122.2, lat = 47.6, zoom = 10)
addGeoJSON() will also accept a string, e.g.
geojson_str <- paste0(readLines(url), collapse = "")
then pass that to addGeoJSON
Related
I'm using addgeoJson function for the india map. I have data that I got it from here
https://gadm.org/download_country.html
for example I'm using this data
This is a json file and I read that json file and pass it to addGeoJson function.
library(jsonlite)
library(leaflet)
url <- "https://raw.githubusercontent.com/openseattle/seattle-boundaries/master/data/zip-codes.geojson"
geojson <- fromJSON(url, simplifyVector = FALSE)
leaflet() %>%
addTiles() %>%
addGeoJSON(geojson) %>%
setView(lng = -122.2, lat = 47.6, zoom = 10)
So I need to popup the names when I click on a particular state or city here. It should give some information when we click on it.
Is this possible to do it? and how?
The information you are looking for is stored deep in the structure of a geojson file (list). See for instance the first object of your dataset
geojson$features[[1]]$properties
Luckily there is a easier way to deal with it.
Use the package leaflet.extra, function addGeoJSONv2 specifying your label under argument popupProperty
library(leaflet.extras)
library(jsonlite)
library(leaflet)
url <- "https://raw.githubusercontent.com/openseattle/seattle-
boundaries/master/data/zip-codes.geojson"
geojson_fil <- fromJSON(url, simplifyVector = FALSE)
leaflet() %>%
addTiles() %>%
setView(lng = -122.2, lat = 47.6, zoom = 10) %>%
addGeoJSONv2(geojson_fil,
popupProperty = 'ZCTA5CE10')
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.
My code
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
I am trying to extract data from a WMS-layer.
As an example, I would like to analyse whether or not a Natura2000 area is touched by my area and what the specifics are of the Natura2000 area.
The WMS-layer of the Natura2000 area can be found at:
https://geodata.nationaalgeoregister.nl/natura2000/ows?service=WMS&request=GetLegendGraphic&format=image/png&width=20&height=20&layer=natura2000"
Let's say my area is a circle with a radius of 7500 meters around a certain x- and y-coordinate;
I was trying to get this done with the leaflet-package, but it seems more a tool to show information, instead of analysing information.
x.WGS=6.662226
y.WGS=52.53206
leaflet() %>% setView(x.WGS, y.WGS, zoom = 11) %>%
addTiles() %>%
addMarkers(lng = x.WGS, lat = y.WGS)%>%
addWMSTiles(
"https://geodata.nationaalgeoregister.nl/natura2000/ows?service=WMS&request=GetLegendGraphic&format=image/png&width=20&height=20&layer=natura2000",
layers = "natura2000",
options = WMSTileOptions(format = "image/png", transparent = TRUE),
attribution = "") %>%
addCircles(lng = x.WGS, lat = y.WGS, weight = 1,
radius = 7500)
I would like it to return two things. Is any Natura2000-area touched by my area? and which areas are that, in other words, what are their names. If I load the WMS-layer in Qgis the name of an Natura2000-area should be under naam_n2k.
In my example, the answer should be that there are two Natura2000 area's touched by my area and the names of these Natrua2000 area's are Vecht- en Beneden-Reggegebied and Engbertsdijksvenen.
The leaflet package is a R package to access leaflet functionality,
one of the most popular open-source JavaScript libraries for displaying interactive maps. More info: https://rstudio.github.io/leaflet/
As #IvanSanchez notes, a Web Map Service (WMS) is a map that you can load in your own application. See this as a georeferenced image/picture without information about the actual polygons, shapes etc.
If you want to do some analysis with polygons or retrieve information, you might need a Web Feature Service (WFS).
First of all, this is the code to load the WMS correctly.
# corrected WMS version
library(leaflet)
library(leaflet.extras) # for WMS legend
x.WGS=6.662226
y.WGS=52.53206
leaflet() %>% setView(x.WGS, y.WGS, zoom = 11) %>%
addTiles() %>%
addMarkers(lng = x.WGS, lat = y.WGS)%>%
addWMSTiles(
baseUrl = "https://geodata.nationaalgeoregister.nl/natura2000/ows?service=WMS",
layers = "natura2000",
options = WMSTileOptions(format = "image/png", transparent = TRUE),
attribution = "") %>%
addCircles(lng = x.WGS, lat = y.WGS, weight = 1,
radius = 7500) %>%
addWMSLegend(uri ="https://geodata.nationaalgeoregister.nl/natura2000/ows?service=WMS&request=GetLegendGraphic&format=image%2Fpng&width=20&height=20&layer=natura2000")
Secondly, to answer your question: we can add a CQL query with a geometry filter to a WFS request.
Note that this is possible in your specific case, but this is not standard for all WFS services.
# Since you want to do spatial analysis on features, we load the sf package
# more info: https://r-spatial.github.io/sf/
library(sf)
# we convert your point coordinates to the native CRS of the WFS layer:
# make point and assign WGS84 CRS
x <- st_point(c(x.WGS,y.WGS))
x <- st_sfc(x) %>% st_set_crs(NA) %>% st_set_crs(4326)
# transform to EPSG::28992 // Amersfoort RD is default CRS for the wfs layer
x_RD <- st_transform(x,28992)
# The WFS allows spatial filtering (this is not always the case)
# so you can use a cql filter with a distance around your point:
# cql_filter=dwithin(natura2000:geom,point(241514 505696.5),7500,meters)
# combining and encoding the cql filter for a valid WFS url:
WFS_url <- paste0("http://geodata.nationaalgeoregister.nl/natura2000/wfs?",
"&service=wfs&version=2.0.0&request=GetFeature&",
"typeName=natura2000:natura2000&cql_filter=",
URLencode(
paste0("dwithin(natura2000:geom,",
st_as_text(x_RD),
",7500, meters)"),
reserved = FALSE),
"&outputFormat=application/json"
)
# get WFS feature
natura2000 <- st_read(WFS_url)
# Transform to WGS84
natura2000_wgs84 <- st_transform(natura2000,4326)
# load data in leaflet
leaflet() %>%
addTiles() %>%
addMarkers(lng = x.WGS, lat = y.WGS) %>%
addCircles(lng = x.WGS, lat = y.WGS, weight = 1,
radius = 7500) %>%
addPolygons(data = natura2000_wgs84,
label = ~naam_n2k,
popup = ~naam_n2k)
Using leaflet in shiny to make an interactive map. Pulling data for popups from a CSV:
Row on CSV:
Name lat lng
Tufts 42.349598 -71.063541
Code on R for markers:
m %>% addMarkers(~lng, ~lat, icon = custommarker1 popup = ~htmlEscape(Name))
This returns marker in correct spot with popup displaying 'tufts'
Wondering if there is a way to encode a hyperlink into the popup directly in the CSV?Oor to put plain text as a new CSV column and have R/Shiny then turn it into a hyperlink.
Very new to shiny/leaflet and would appreciate any help!
Just include the link in the popup as html:
output$mymap <- renderLeaflet({
m <- leaflet() %>%
addTiles() %>% # Add default OpenStreetMap map tiles
addMarkers(lng=174.768, lat=-36.852, popup= ' R ')
m # Print the map
})
You can set the popup equal to a column in your dataframe as well. If your dataframe was called df and it contained longitude = long, latitude= lat, and urls = link :
output$mymap <- renderLeaflet({
m <- leaflet() %>%
addTiles() %>% # Add default OpenStreetMap map tiles
addMarkers(lng=df$long, lat=df$lat, popup= df$link)
m # Print the map
})
If you want the link to be a hyperlink, I have used this
popup = ~paste("", "click here", "")
provided your data has a column called link where the urls are.
m <- leaflet() %>%
addPolygons(data = SP) %>%
addTiles()
for(k in 1:nrow(rfcCleaned))
{
lat = rfcCleaned$Latitude[k]
long = rfcCleaned$Longitude[k]
addMarkers(m, lng, lat, popup = as.character(k))
}
m
addMarkers does not print any pop-ups. I even tried format(k) in place of as.character(k)). For the following code a single pop-up is displayed as expected. Am I doing anything wrong?
m <- leaflet() %>%
addTiles() %>% # Add default OpenStreetMap map tiles
addMarkers(lng=174.768, lat=-36.852, popup="The birthplace of R")
m # Print the map
Thanks in advance
To add markers it is not required to bind them in loop. You can simply add them to piped command after tiles.
Here is the sample data i have used to display markers.
id slon slat
2 93.089 25.054
3 93.038 24.939
4 92.988 24.825
5 92.937 24.710
6 92.886 24.596
7 92.835 24.482
R query
library(leaflet)
ex1map<-leaflet() %>% addTiles() %>% addMarkers(ex1map, lat = ex1$slat,lng = ex1$slon,popup = as.character(ex1$id))
In the below picture i am able to see popup of their respective id.
In case if you don't want to add another column of id, here is another alternative solution.
data ex2 has records provided by you in above comments.
ex2map <- leaflet() %>% addTiles() %>% addMarkers(ex2, lat = ex2$Latitude,lng = ex2$Longitude,popup = as.character(1:nrow(ex2)))
Note: your data has duplicate records,so popups will be displayed for the last duplicate record found