Wilcar
Wilcar

Reputation: 2513

R How to convert MultiLineString GeoJson file to dataframe with long and lat columns?

I have a MultiLineString Geogeson file exported from gqig gis software. A small example :

{
"type": "FeatureCollection",
"name": "route1",
 "crs": { "type": "name", "properties": { "name": "urn:ogc:def:crs:EPSG::3857" 
 } },
 "features": [
 { "type": "Feature", "properties": { "FID": 0 }, "geometry": { "type": 
 "MultiLineString", "coordinates": [ [ [ 1936131.287994222715497, 
 -4335318.772792792879045 ], [ -2633407.770391199737787, 
  1763382.609922708477825 ], [ -2922369.195528693497181, 
  4600947.908943663351238 ], [ -1640888.092745035886765, 
  5275789.498084637336433 ], [ -361201.781421858817339, 5970373.793290910311043 
  ], [ -361201.781421858817339, 5970373.793290910311043 ] ] ] 
 } }
]
}

How can I convert it in a dataframe binding nodes with long and lat colunms ? Expected result :

node    long                    lat 
1   1936131.287994222715497    -4335318.772792792879045 
2   -2633407.770391199737787    1763382.609922708477825 

What I tried (creating a list) :

  route1 <- jsonlite::fromJSON(readr::read_file("routes/route1.geojson"))

Upvotes: 2

Views: 603

Answers (2)

SymbolixAU
SymbolixAU

Reputation: 26248

library(sf) can read GeoJSON. This will give you an sf object. If you want the coordinates you can use the st_coordinates() function.

library(sf)

sf <- sf::st_read( geo, quiet = T )
df <- as.data.frame( sf::st_coordinates( sf ) )

#            X        Y L1 L2
# 1  1936131.3 -4335319  1  1
# 2 -2633407.8  1763383  1  1
# 3 -2922369.2  4600948  1  1
# 4 -1640888.1  5275789  1  1
# 5  -361201.8  5970374  1  1
# 6  -361201.8  5970374  1  1

This extra L1 and L2 columns tell you to which linestring within the MULTILINESTRING each coordinate pair belong.

Upvotes: 3

jay.sf
jay.sf

Reputation: 72613

If you examine the structure of the obtained list with str(route1) you can see that the data is stored in an array, which you can extract.

a <- route1$features$geometry$coordinates[[1]]
a

# , , 1
# 
#         [,1]     [,2]     [,3]     [,4]      [,5]      [,6]
# [1,] 1936131 -2633408 -2922369 -1640888 -361201.8 -361201.8
# 
# , , 2
# 
#          [,1]    [,2]    [,3]    [,4]    [,5]    [,6]
# [1,] -4335319 1763383 4600948 5275789 5970374 5970374

Now, just do a cbind() to get what you want.

cbind(a[, , 1], a[, , 2])
#            [,1]     [,2]
# [1,]  1936131.3 -4335319
# [2,] -2633407.8  1763383
# [3,] -2922369.2  4600948
# [4,] -1640888.1  5275789
# [5,]  -361201.8  5970374
# [6,]  -361201.8  5970374

Or as data frame:

d <- data.frame(long=a[, , 1], lat=a[, , 2])
d <- cbind(node=rownames(d), d)
d
#   node       long      lat
# 1    1  1936131.3 -4335319
# 2    2 -2633407.8  1763383
# 3    3 -2922369.2  4600948
# 4    4 -1640888.1  5275789
# 5    5  -361201.8  5970374
# 6    6  -361201.8  5970374

Upvotes: 2

Related Questions