如何用R语言将MultiLineString GeoJSON转换为含经纬度列的数据框?
Hey there! Let's turn that QGIS-exported MultiLineString GeoJSON into the structured data frame you need. You’ve already nailed the first step by reading the file with jsonlite and readr—now let’s unpack the nested coordinate data and reshape it.
Step 1: Extract the Coordinate Points
Your GeoJSON’s geometry is a MultiLineString, which stores coordinates as a nested list. For your example (with a single LineString inside the MultiLineString), we can directly pull out the point coordinates:
# Your existing code to read the file route1 <- jsonlite::fromJSON(readr::read_file("routes/route1.geojson")) # Extract the nested coordinate list: [[1]][[1]] targets the first (and only) LineString's points coordinate_points <- route1$features$geometry$coordinates[[1]][[1]]
Step 2: Reshape into Your Desired Data Frame
Now we’ll convert the coordinate matrix to a data frame, rename columns, add the node sequence, and reorder columns to match your expected output:
library(dplyr) # Convert to data frame, rename columns, add node numbers route_df <- as.data.frame(coordinate_points) %>% rename(long = V1, lat = V2) %>% # Rename default V1/V2 to long/lat mutate(node = row_number()) %>% # Add sequential node IDs select(node, long, lat) # Reorder columns to match your desired structure # Check the result print(route_df)
This will give you exactly the output you showed (with all points included):
node long lat 1 1 1936131.29 -4335318.77 2 2 -2633407.77 1763382.61 3 3 -2922369.20 4600947.91 ...
Handling Multiple LineStrings (If Needed)
If your MultiLineString ever contains multiple separate LineStrings (e.g., a route with disconnected segments), use purrr to flatten all points into a single data frame while keeping the sequential node order:
library(purrr) library(dplyr) all_coords <- route1$features$geometry$coordinates[[1]] %>% map_df(~as.data.frame(.x) %>% rename(long = V1, lat = V2)) %>% mutate(node = row_number()) %>% select(node, long, lat)
Quick Note on Coordinate System
Your GeoJSON uses EPSG:3857 (Web Mercator, meter-based coordinates). If you ever need to convert these to standard WGS84 latitude/longitude (EPSG:4326), you can use the sf package to handle the transformation easily:
library(sf) # Convert to sf object, transform coordinates, then extract to data frame route_sf <- st_read("routes/route1.geojson") %>% st_transform(4326) %>% st_coordinates() %>% as.data.frame() %>% rename(long = X, lat = Y) %>% mutate(node = row_number()) %>% select(node, long, lat)
内容的提问来源于stack exchange,提问作者Wilcar

