How to load *part* of a multifeature geojson file in R?

青春壹個敷衍的年華 提交于 2019-12-12 16:18:57

问题


I have a geojson that is a FeatureCollection containing 2 geographic data types: a LineString and a waypoint - see the raw file here - this is how it looks on GitHub:

I want to load only only the LineString, so this is what I do:

library(RCurl)
obj <- getURL("https://raw.githubusercontent.com/Robinlovelace/stplanr/master/inst/extdata/route_data.geojson")
writeLines(obj, "/tmp/obj.geojson")
obj <- readLines("/tmp/obj.geojson")
just_lines <- obj[14:(length(obj) - 28)]
just_lines[1] <- paste0("{",  just_lines[1])
just_lines[length(just_lines)] <- "}"
writeLines(just_lines, "/tmp/just_lines.geojson")

Now we have removed the pesky lines at the beginning and end of the file, it's a nicely formed GeoJSON file that we can load and plot, yay:

library(rgdal)
route <- readOGR("/tmp/just_lines.geojson", layer = "OGRGeoJSON")
plot(route)

Except it should be obvious to any R user that this is a very clunky and inefficient way of doing this involving too many lines of code and unnecessary reading and writing to the hard disc. There must be another way!

Options I've looked at

  • geojsonio
  • jsonlite
  • leaflet, which can display the FeatureCollection but seemingly not extract its parts.

Context

I'm creating a package for sustainable transport planning, stplanr. A function to find cycling routes (like in the image below) needs to load in the FeatureCollection geojson data from the CycleStreets.net api.


回答1:


Read the data using jsonlite direct from the URL:

 obj <- jsonlite::fromJSON("https://raw.githubusercontent.com/Robinlovelace/stplanr/master/inst/extdata/route_data.geojson")

Convert the first object in the collection to SpatialLines:

 sl = SpatialLines(list(Lines(list(Line(obj$features[1,]$geometry$coordinates[[1]])),ID=1)))
 plot(sl)

That assumes the feature is a single line string.

To make a SpatialLinesDataFrame with the attributes:

 sldf=SpatialLinesDataFrame(sl=sl,data=obj$features[1,]$properties)

Should probably also give it a CRS:

 proj4string(sldf)=CRS("+init=epsg:4326")



回答2:


I don't know if this is possible in LeafletR but Leaflet's L.GeoJSON layer has a filter method which can render (or not render) a collection's features based on the properties the feature has. Some code:

L.geoJson(geojson, {
  'filter': function (feature) {
    return feature.geometry.type === 'LineString'
  }
});

An example: http://plnkr.co/edit/RXIO0X?p=preview

Reference: http://leafletjs.com/reference.html#geojson-filter



来源:https://stackoverflow.com/questions/29066198/how-to-load-part-of-a-multifeature-geojson-file-in-r

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!