Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use the addGeoJSON() feature in R for Leaflet?

Tags:

r

leaflet

geojson

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

like image 543
Dazzle Avatar asked Aug 03 '15 23:08

Dazzle


1 Answers

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)

enter image description here

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)

enter image description here

like image 121
sckott Avatar answered Sep 19 '22 22:09

sckott