Search code examples
rgeospatialgeojson

Create single column GeoJSON using R


I am trying to create an excel file, ready for use within Power Apps Geospatial features: https://learn.microsoft.com/en-us/power-apps/maker/canvas-apps/geospatial-map-draw-shapes#import-geojson-shapes-into-a-map

This needs a single excel file, where each row is a seperate feature, which has a GeoJSON column which is a self contained GeoJSON object.

I can't work out how to do this using R and R Studio. My input file is a GeoJSON, but could be a shapefile.

I have tried a number of methods, but on each occasion I am tripping up with trying to get the features to export


Solution

  • Through brute force trying only, I've found a way to do this:

    # Load the required library
    library(sf)
    library(geojsonsf)
    library(jsonlite)
    library(dplyr)
    library(openxlsx)
    
    # Set column name so it can be easily amended for different files.
    # Could replace this with extraction from GeoJSON?
    colnameselect <- ""
    
    # Read the GeoJSON file
    geojson <- st_read("input.geojson")
    
    # Simplify the file to a 100m resolution
    shp_simpl <- st_simplify(geojson, 
                             preserveTopology = FALSE, 
                             dTolerance = 100)
    
    
    geojson_new <- sf_geojson(shp_simpl, atomise = T)
    
    geojson_new_unlist <- lapply(geojson_new, unlist)
    
    geojson_df <- do.call(rbind.data.frame, geojson_new_unlist)
    names(geojson_df)[1] <- "GeoJSON"
    
    shp_join <- shp_simpl %>% select(all_of(colnameselect))
    shp_join <- st_drop_geometry(shp_join)
    
    join_list <- cbind(shp_join,geojson_df)
    
    openxlsx::write.xlsx(join_list, "test_Geojson.xls")
    

    This seems to do the job! Thanks to everyone for their help - lots of different ideas all helped me sort it out. Particularly the unlisting of the GeoJSON