【问题标题】:Convert Lat/Lon to County Codes using FCC API使用 FCC API 将 Lat/Lon 转换为县代码
【发布时间】:2020-11-05 15:23:56
【问题描述】:

感谢@caldwellst 和@rohit,我之前想出了如何使用 FCC API (Apply an API Function over 2 columns of Dataframe, Output a Third Column) 将纬度/经度转换为县级 FIPS 代码。不幸的是,FCC 修改了 API,我无法弄清楚如何修复代码以再次工作。

这里是新 API 的链接:https://geo.fcc.gov/api/census/

这是我的数据框:

> head(df_coords)

# A tibble: 6 x 3
     lon   lat censusYear
   <dbl> <dbl>      <dbl>
1 -112.   33.4       2010
2  -73.2  44.5       2010
3  -88.2  41.9       2010
4  -88.2  41.9       2010
5  -88.4  41.9       2010
6  -77.1  39.0       2010

这是我之前借用/改编的函数以及运行它的命令:

geo2fips <- function(latitude, longitude) { 
  url <- "https://geo.fcc.gov/api/census/block/find?format=json&latitude=%f&longitude=%f"
  url <- sprintf(url, latitude, longitude)
  json <- RCurl::getURL(url)
  json <- RJSONIO::fromJSON(json)
  as.character(json$County['FIPS'])
}

df_fips$county_fips <- mapply(geo2fips, df_fips$lat, df_fips$lon)

这是我运行它时收到的错误消息:


 Error in function (type, msg, asError = TRUE)  : 
  Unknown SSL protocol error in connection to geo.fcc.gov:443 

谁能帮我解决这个问题?我想这可能与人口普查年的要求有关,所以我尝试修改代码如下,但它返回了相同的错误消息:

 geo2fips <- function(latitude, longitude, censusYear) { 
+   url <- "https://geo.fcc.gov/api/census/block/find?format=json&latitude=%f&longitude=%f&censusYear=%f"
+   url <- sprintf(url, latitude, longitude, censusYear)
+   json <- RCurl::getURL(url)
+   json <- RJSONIO::fromJSON(json)
+   as.character(json$County['FIPS'])
+ }
> df_coords$county_fips <- mapply(geo2fips, df_coords$lat, df_coords$lon, df_coords$censusYear)
 Error in function (type, msg, asError = TRUE)  : 
  Unknown SSL protocol error in connection to geo.fcc.gov:443 
> 

非常感谢任何可以提供帮助的人。 -迈克

【问题讨论】:

    标签: r json function api-design


    【解决方案1】:

    URL 和参数略有变化 - 您可以使用:

    geo2fips <- function(latitude, longitude) { 
      url <- "https://geo.fcc.gov/api/census/area?lat=%f&lon=%f&format=json"
      res <- jsonlite::fromJSON(sprintf(url, latitude, longitude))[["results"]][["county_fips"]]
      unique(res)
    }
    

    如果您使用jsonlite 包而不是RSJONIO,您还可以稍微简化一些事情,因为前者直接接受连接。

    【讨论】:

    • 太棒了!出于某种原因,尽管结果 tibble 中的county_fips 列正在显示一个列表,有时是重复字符。你知道它为什么会这样做吗?提前致谢!!!
    • 我通过取消嵌套列表来修复它,使用 distinct() 删除重复项,然后将整个内容重新连接到我的数据框中。所以这不是完全必要的,但如果它是一个问题,那就很好奇了。非常感谢您的帮助!
    • 一些查询返回多个记录,根据有限的样本坐标,这些记录似乎在某些字段上有所不同。如果您只在 FIPS 字段之后,您可以使用 unique() 将结果包装在函数中,这应该可以解决问题(尽管我对这些数据的了解不够多,因此不会有坐标实例生成多个不同的 FIPS 代码)。
    猜你喜欢
    • 1970-01-01
    • 2014-07-26
    • 1970-01-01
    • 1970-01-01
    • 2022-12-14
    • 2015-10-07
    • 1970-01-01
    • 1970-01-01
    • 2011-03-31
    相关资源
    最近更新 更多