Could someone please explain how the addGeoJSON() feature works in R, I cannot make sense of the documentation.
?addGeoJSON => (map, geojson, layerId = NULL)
What is geojson and layerId?
I was able to import my GeoJSON using GDAL: a1 <- readOGR(dsn = "myData.geojson", layer = "OGRGeoJSON")
How can I access the columns to plot x, y with leaflet addGeoJSON() ?
Thanks
The first argument to addGeoJSON
is the leaflet object, created from a call to leaflet()
. e.g.,
url <- "https://raw.githubusercontent.com/glynnbird/usstatesgeojson/master/california.geojson"
geojson <- jsonlite::fromJSON(url)
library("leaflet")
leaflet() %>%
addTiles() %>%
setView(lng = -98.583, lat = 39.833, zoom = 3) %>%
addGeoJSON(geojson)
You can just replace your geojson read in via readOGR
with the geojson
object I created
With readOGR()
library("leaflet")
library("rgdal")
url <- "https://raw.githubusercontent.com/glynnbird/usstatesgeojson/master/california.geojson"
res <- readOGR(dsn = url, layer = "OGRGeoJSON")
leaflet() %>%
addTiles() %>%
setView(lng = -98.583, lat = 39.833, zoom = 3) %>%
addPolygons(data = res)
You should replace addPolygons(data = res)
with addPolygons(data = res, lng = "feature.properties.long", lat = "feature.properties.lat")
Should work for your example above. Both likely give back a SpatialPolygonsDataFrame
class, which you need to pass to the data
parameter either in leaflet()
or addPolygons()
.
Okay, if you're reading a geojson file from disk, with points, then e.g.,
geojson <- '{
"type": "FeatureCollection",
"features" :
[
{
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates": [ -123, 49 ]
},
"properties": {
"a_property": "foo",
"some_object": {
"a_property": 1,
"another_property": 2
}
}
}
]
}'
writeLines(geojson, "file.geojson")
res <- readOGR(dsn = "file.geojson", layer = "OGRGeoJSON")
leaflet() %>%
addTiles() %>%
setView(lng = -123, lat = 49, zoom = 6) %>%
addMarkers(data = res)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With