Im having difficulty using R to load the geometries from a kml to a feature layer stored in AGOL. Im using sf in R to process the kml file, convert it to a geojson, take the geometry from the geojson, add it to a adds package, then load the package to the feature layer via the applyEdits request. However, whenever I do I consistently get errors saying that my geometry package isn't sturctured correctly. I can get it to work with a mock polygon I create via sf, but never when using an existing file.
url <- "https://services1.arcgis.com/*********/arcgis/rest/services/Test_Load/FeatureServer/0"
# Read KML file into an sf object
kml_data <- sf::st_read("C:/git/APEX_2024/Zip_Map_Attributes/Data/KML Files/AK_Hwy_Johnson_APE_STIP33824.kml")
geojson <- sf_geojson(kml_data)
parsed_geojson <- jsonlite::fromJSON(geojson)
polygon <- list(
geometry = list(
rings = parsed_geojson$features$geometry$coordinates,
spatialReference = list(
wkid = 4326
)
),
attributes = list(
Test = "Added from R"
)
)
edits <- list(
adds = list(polygon)
)
# Add token to the headers if necessary
headers <- c(
"Content-type" = "application/x-www-form-urlencoded",
"Accept" = "text/plain"
)
response <- POST(
url = paste0(url, "/applyEdits"),
query = list(
f = "json",
adds = toJSON(edits$adds),
updateParameters = toJSON(list()) # Add an empty updateParameters to fix the "Invalid parameters" error
),
add_headers(.headers=headers)
)