如何在R中加载多功能geojson文件的“一部分"? [英] How to load *part* of a multifeature geojson file in R?

查看:286
本文介绍了如何在R中加载多功能geojson文件的“一部分"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个geojson,它是一个FeatureCollection,其中包含2种地理数据类型:LineStringwaypoint-请参阅原始文件

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:

我只想加载LineString,所以这就是我要做的:

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")

现在我们已经删除了文件开头和结尾的讨厌的行,这是一个格式正确的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)

除了对于任何R用户来说显而易见的是,这是一种非常笨拙且效率低下的方法,涉及过多的代码行以及不必要的对硬盘的读写.一定有另一种方式!

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!

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

我正在创建一个用于可持续交通规划的软件包, stplanr . 功能,以查找自行车路线(如下图所示) )需要从以下位置加载 FeatureCollection geojson数据 CycleStreets.net api .

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.

推荐答案

直接从URL使用jsonlite读取数据:

Read the data using jsonlite direct from the URL:

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

将集合中的第一个对象转换为SpatialLines:

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.

要创建具有以下属性的SpatialLinesDataFrame:

To make a SpatialLinesDataFrame with the attributes:

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

还应该为其提供CRS:

Should probably also give it a CRS:

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

这篇关于如何在R中加载多功能geojson文件的“一部分"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆