简体   繁体   English

从a leaflet map导入数据作为sf object in R

[英]Import data from a leaflet map as an sf object in R

I want to import data as an sf object in R from a leaflet map. The map is this site: https://erickgn.github.io/mapafc/ I also have the HTML from the map as following: https://raw.githubusercontent.com/erickgn/mapafc/main/index.html . I want to import data as an sf object in R from a leaflet map. The map is this site: https://erickgn.github.io/mapafc/ I also have the HTML from the map as following: https://raw .githubusercontent.com/erickgn/mapafc/main/index.html

I also have the HTML from the map as following: https://raw.githubusercontent.com/erickgn/mapafc/main/index.html .我还有来自 map 的 HTML,如下所示: https://raw.githubusercontent.com/erickgn/mapafc/main/index.html

Then you have everything.然后你就拥有了一切。 Either save the page locally, either scrape it using xml2 package. If you look on the page source, you can find something like:要么将页面保存在本地,要么使用xml2 package 抓取它。如果您查看页面源代码,您会发现类似以下内容:

geo_json_b75320e180b34bb88a8a9025dff8675e_add({"bbox": [-44.447264,
 -23.03329, -41.6957233, -22.2949485],[...]

as seems that are your features, you can read it with sf::st_read or jsonlite package.看起来这是您的功能,您可以使用 sf::st_read 或jsonlite package 阅读它。

A small example for the first JSON:第一个 JSON 的一个小例子:

library(rvest)
url <- "https://raw.githubusercontent.com/erickgn/mapafc/main/index.html"
text <- html_text(read_html(url))

Now we have to locate two strings which are before and after json and take the part between.现在我们必须找到 json 之前和之后的两个字符串并取其间的部分。 Please note +1, -22 -- the first one is quite obvious, the second one is a bit of trying to remove unnecessary new lines etc.请注意+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)

And finally let's convert json to R objects:最后让我们将 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
[...]

You can repeat similar steps for next.json(s).您可以对 next.json(s) 重复类似的步骤。

And reading with sf package:并阅读sf package:

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)

Regards, Grzegorz问候,格热戈兹

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM