我想从传单地图将数据作为 R 中的 sf 对象导入。地图是这个网站:https://erickgn.github.io/mapafc/我还有地图中的 HTML,如下所示:https://raw.githubusercontent.com/erickgn/mapafc/main/index.html html.
我还有地图中的 HTML,如下所示:https://raw.githubusercontent.com/erickgn/mapafc/main/index.html.
那么你就拥有了一切。要么将页面保存在本地,要么使用
xml2
包抓取它。如果您查看页面源代码,您可以找到类似以下内容:
geo_json_b75320e180b34bb88a8a9025dff8675e_add({"bbox": [-44.447264,
-23.03329, -41.6957233, -22.2949485],[...]
这似乎是您的功能,您可以使用 sf::st_read 或
jsonlite
包来读取它。
第一个 JSON 的小例子:
library(rvest)
url <- "https://raw.githubusercontent.com/erickgn/mapafc/main/index.html"
text <- html_text(read_html(url))
现在我们必须找到 json 之前和之后的两个字符串 取之间的部分。请注意
+1, -22
——第一个非常明显,第二个有点试图删除不必要的新行等。
library(stringi)
st <- stri_locate_first_fixed(text, "geo_json_b75320e180b34bb88a8a9025dff8675e_add(")[2]+1
fi <- stri_locate_first_fixed(text, "geo_json_b75320e180b34bb88a8a9025dff8675e.bindTooltip(")[1]-22
json <- substring(text, st, fi)
最后让我们将 json 转换为 R 对象:
jsonlite::fromJSON(json)
#> $bbox
#> [1] -44.44726 -23.03329 -41.69572 -22.29495
#>
#> $features
#> bbox
#> 1 -43.59792, -22.82906, -43.58869, -22.82160
#> 2 -43.38023, -22.96123, -43.37173, -22.95453
#> 3 -43.50182, -23.03329, -43.49279, -23.02227
#> 4 -43.29931, -22.99099, -43.29163, -22.98606
[...]
您可以对下一个 json 重复类似的步骤。
并使用
sf
包阅读:
library(sf)
a <- st_read(json)
#> Reading layer `OGRGeoJSON' from data source
#> [...]
#> using driver `GeoJSON'
#> Simple feature collection with 249 features and 16 fields
#> Geometry type: POLYGON
#> Dimension: XY
#> Bounding box: xmin: -44.44726 ymin: -23.03329 xmax: -41.69572 ymax: -22.29495
#> Geodetic CRS: WGS 84
plot(a$geometry)
问候, 格热戈日