我有一个数据帧,其中我的第一列是geojson字符串,第二列是该位置的度量。如果将第一列中的字符串粘贴到https://geojson.io/中,则可以正确呈现
我希望在R中使用leaflet绘制此图,如以下链接所示。https://rstudio.github.io/leaflet/json.html
不幸的是,我不知道如何将我的数据转换成一种可以与leaflet一起工作的格式(看起来像是一个sp对象)。
数据行示例:
geojson <- '{"type": "Polygon", "coordinates": [[ [-104.05, 48.99], [-97.22, 48.98], [-96.58, 45.94], [-104.03, 45.94], [-104.05, 48.99] ]]}'
measure1 <- 10000
test_df <- data.frame(geojson, measure1)
test_df$geojson <- as.character(test_df$geojson)在这种情况下,任何其他关于最佳实践的技巧也将不胜感激。
发布于 2017-03-27 05:30:55
可以肯定的是,leaflet要求geojson有一个properties插槽。你可以用geojson pkg来做这件事,例如
library(leaflet)
library(geojson)
geojson <- '{"type": "Polygon", "coordinates": [[ [-104.05, 48.99], [-97.22, 48.98], [-96.58, 45.94], [-104.03, 45.94], [-104.05, 48.99] ]]}'
geojson <- geojson::properties_add(geojson, population = 10000)当然,您也可以手动添加属性槽来操作字符串,但我们使用的是jqr,这是一个快速的JSON解析器,它将确保正确地执行此操作
measure1 <- 10000
df <- data.frame(geojson, measure1, stringsAsFactors = FALSE)
leaflet() %>%
addTiles() %>%
addGeoJSON(df$geojson) %>%
setView(-100, 47.6, 7)

发布于 2018-04-18 11:19:41
您可以使用library(geojsonsf)将geojson列转换为sfc列(然后从中创建sf对象)
数据
## construct data (I've added an extra row)
geojson <- c('{"type": "Polygon", "coordinates": [[ [-104.05, 48.99], [-97.22, 48.98], [-96.58, 45.94], [-104.03, 45.94], [-104.05, 48.99] ]]}',
'{"type": "Polygon", "coordinates": [[ [-103.05, 47.99], [-96.22, 47.98], [-93.58, 41.94], [-104.03, 45.94], [-103.05, 47.99] ]]}')
measure1 <- c(10000,20000)
test_df <- data.frame(geojson, measure1)
test_df$geojson <- as.character(test_df$geojson)sfc列
## create an 'sfc' column
test_df$geojson <- geojsonsf::geojson_sfc(test_df$geojson)sf对象
使用library(sf)将其转换为sf对象
library(sf)
sf <- sf::st_sf(test_df)
sf
# Simple feature collection with 2 features and 1 field
# geometry type: POLYGON
# dimension: XY
# bbox: xmin: -104.05 ymin: 41.94 xmax: -93.58 ymax: 48.99
# epsg (SRID): 4326
# proj4string: +proj=longlat +datum=WGS84 +no_defs
# measure1 geojson
# 1 10000 POLYGON ((-104.05 48.99, -9...
# 2 20000 POLYGON ((-103.05 47.99, -9...绘图
在这里,您可以对这个sf对象做任何您想做的事情。
library(leaflet)
leaflet() %>%
addTiles() %>%
addPolygons(data = sf)

library(googleway)
set_key("YOUR_GOOGLE_MAP_KEY")
google_map() %>%
add_polygons(data = sf)

https://stackoverflow.com/questions/43031194
复制相似问题