Reputation: 4407
My question is how to read a geojson file containing feature collections to leaflet-shiny. I have seen joe's github https://github.com/jcheng5/leaflet-shiny/blob/master/inst/examples/geojson/server.R but he did not use an external dataset but created the geojson manually. i am confused whether
Upvotes: 1
Views: 2545
Reputation: 876
You're probably looking to be able to manipulate the GeoJSON file directly in R-Shiny
and R
as opposed to reading a static file.
As previously mentioned, you can feed a string containing the GeoJSON to leaflet-shiny
such as this GeoJSON FeatureCollection:
{
"type": "FeatureCollection",
"features": [
{
"type": "Feature",
"properties": {"party": "Republican"},
"id": "North Dakota",
"geometry": {
"type": "Polygon",
"coordinates": [[
[-104.05, 48.99],
[-97.22, 48.98],
[-96.58, 45.94],
[-104.03, 45.94],
[-104.05, 48.99]
]]
}
},
{
"type": "Feature",
"properties": {"party": "Democrat"},
"id": "Colorado",
"geometry": {
"type": "Polygon",
"coordinates": [[
[-109.05, 41.00],
[-102.06, 40.99],
[-102.03, 36.99],
[-109.04, 36.99],
[-109.05, 41.00]
]]
}
}
]
}
Then you can use RJSONIO::fromJSON
to read this object in the format provided in the example and manipulate it in R
such as this (Note: it appears that you have to add styles after reading the GeoJSON file as opposed to reading a GeoJSON FeatureCollection file that already has styles):
geojson <- RJSONIO::fromJSON(fileLocation)
geojson[[2]][[1]]$properties$style <- list(color = "red",fillColor = "red")
geojson[[2]][[2]]$properties$style <- list(color = "blue",fillColor = "blue")
geojson$style <- list(weight = 5,stroke = "true",fill = "true",opacity = 1,fillOpacity = 0.4)
This will give you the same R
object if you had just entered this:
geojson <- list(
type = "FeatureCollection",
features = list(
list(
type = "Feature",
geometry = list(type = "MultiPolygon",
coordinates = list(
list(
list(
c(-109.05, 41.00),
c(-102.06, 40.99),
c(-102.03, 36.99),
c(-109.04, 36.99),
c(-109.05, 41.00)
)
)
)
),
properties = list(
party = "Democrat",
style = list(
fillColor = "blue",
color = "blue"
)
),
id = "Colorado"
),
list(
type = "Feature",
geometry = list(type = "MultiPolygon",
coordinates = list(
list(
list(
c(-104.05, 48.99),
c(-97.22, 48.98),
c(-96.58, 45.94),
c(-104.03, 45.94),
c(-104.05, 48.99)
)
)
)
),
properties = list(
party = "Republican",
style = list(
fillColor = "red",
color = "red"
)
),
id = "North Dakota"
)
),
style = list(
weight = 5,
stroke = "true",
fill = "true",
fillOpacity = 0.4
opacity = 1
))
Upvotes: 3
Reputation: 2371
For question 1, refering to the API doc, you can provide instead directly a geojson string instead of a list like in the example.
The provided example also mentionned it with
You can also use a GeoJSON string value instead of a structured GeoJSON object like this one
You can use this recipe to read your GeoJSON file
For question 2, as question 1 is Ok, no issue.
Upvotes: 0