【问题标题】:Import data from a leaflet map as an sf object in R将传单地图中的数据作为 R 中的 sf 对象导入
【发布时间】:2022-11-19 18:07:23
【问题描述】:

我想从传单地图将数据作为 R 中的 sf 对象导入。地图是这个站点:https://erickgn.github.io/mapafc/ 我也有来自地图的 HTML 如下:https://raw.githubusercontent.com/erickgn/mapafc/main/index.html

【问题讨论】:

    标签: html r leaflet gis sf


    【解决方案1】:

    我还有来自地图的 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)
    

    问候, 格热戈日

    【讨论】:

    • 我做了这样的事情,但最后我得到了一个错误- html_document %>% html_node(xpath = '/html/body/pre') %>% html_text() myMap <- FROM_GeoJson(url_file_string = text)
    • 嗨@MariaMittelbach,请查看我上面的扩展答案。
    猜你喜欢
    • 2021-06-02
    • 2020-08-14
    • 2019-01-08
    • 1970-01-01
    • 2018-07-29
    • 2022-11-13
    • 1970-01-01
    • 2018-02-07
    • 1970-01-01
    相关资源
    最近更新 更多