我已经使用 R 来计算 Voronoi 曲面细分,现在我想在 OSM umap 中使用。因为我希望不同的区域能够轻松区分,遵循 他们 github 上的一些提示,我需要一个嵌套字段,在本例中
_umap_options$color
但是当我尝试将这样一个简单的特征集合导出到 geoJSON 文件时,我要么松开嵌套列,要么导出根本不起作用。导出到 JSON 效果很好,但我更喜欢 R 输出可以直接使用的 geoJSON 文件。
这是一个 MWE:
library(osmdata)
library(sf)
library(geojsonsf)
df1 <- data.frame(osm_id=c(1:3), name=c("foo","bar","test"),lon=c(7,8,9),lat=52)
sf1 <- st_as_sf(df1,coords=c("lon","lat"))
df2 <- data.frame(fillColor=c("red","green","blue"))
df1$"_umap_options" <- df2
sf2 <- st_as_sf(df1,coords=c("lon","lat"))
# a simple JSON has the nested information correctly
toJSON(sf2, pretty=TRUE)
# won't accept the object as input
sf_geojson(sf2)
# while the sf without nested columns goes through
sf_geojson(sf1)
# ignores the nested column
st_write(sf2,"/tmp/test.geojson")
st_write 也会发出警告:
在 clean_columns(as.data.frame(obj), FactorAsCharacter) 中: 删除类 data.frame 的列 _umap_options
我是否在我的 data.frames 中遗漏了一些必要的修改以使其成为可能?
使用
st_write()
/ GDAL,如果您只在框架中存储 JSON 字符串就足够了。
来自 GDAL GeoJSON 驱动程序文档:
:(GDAL >= 3.8)默认为AUTODETECT_JSON_STRINGS=[YES/NO]
。如果字符串字段以方括号和大括号开头和结尾,是否尝试将字符串字段解释为 JSON 数组或对象,即使它们没有将其子类型设置为 JSON。YES
library(sf)
#> Linking to GEOS 3.12.1, GDAL 3.8.4, PROJ 9.3.1; sf_use_s2() is TRUE
library(dplyr)
library(jsonlite)
df1 <- data.frame(osm_id=c(1:3), name=c("foo","bar","test"),lon=c(7,8,9),lat=52)
sf1 <- st_as_sf(df1,coords=c("lon","lat"), crs = "WGS84")
df2 <- data.frame(fillColor=c("red","green","blue"))
# use JSON string in _umap_options
sf2 <-
bind_cols(sf1, df2) |>
rowwise() |>
mutate(
`_umap_options` = toJSON(
list(fillColor = fillColor),
auto_unbox = TRUE),
.keep = "unused") |>
ungroup()
sf2
#> Simple feature collection with 3 features and 3 fields
#> Geometry type: POINT
#> Dimension: XY
#> Bounding box: xmin: 7 ymin: 52 xmax: 9 ymax: 52
#> Geodetic CRS: WGS 84
#> # A tibble: 3 × 4
#> osm_id name geometry `_umap_options`
#> <int> <chr> <POINT [°]> <json>
#> 1 1 foo (7 52) "{\"fillColor\":\"red\"}"
#> 2 2 bar (8 52) "{\"fillColor\":\"green\"}"
#> 3 3 test (9 52) "{\"fillColor\":\"blue\"}"
st_write(sf2, "test.geojson")
#> Writing layer `test' to data source `test.geojson' using driver `GeoJSON'
#> Writing 3 features with 3 fields and geometry type Point.
readr::read_file("test.geojson") |> prettify()
生成的 GeoJSON:
{
"type": "FeatureCollection",
"name": "test",
"crs": {
"type": "name",
"properties": {
"name": "urn:ogc:def:crs:OGC:1.3:CRS84"
}
},
"features": [
{
"type": "Feature",
"properties": {
"osm_id": 1,
"name": "foo",
"_umap_options": {
"fillColor": "red"
}
},
"geometry": {
"type": "Point",
"coordinates": [
7.0,
52.0
]
}
},
{
"type": "Feature",
"properties": {
"osm_id": 2,
"name": "bar",
"_umap_options": {
"fillColor": "green"
}
},
"geometry": {
"type": "Point",
"coordinates": [
8.0,
52.0
]
}
},
{
"type": "Feature",
"properties": {
"osm_id": 3,
"name": "test",
"_umap_options": {
"fillColor": "blue"
}
},
"geometry": {
"type": "Point",
"coordinates": [
9.0,
52.0
]
}
}
]
}
创建于 2024-07-27,使用 reprex v2.1.0