Leaflet R derivePolygons missing lat missing long

Leaflet R derivePolygons missing lat missing long

我正在尝试在地图上绘制一些 disease-events 数据的位置。

我用它来导入数据:

ByTown<-readOGR(dsn="C:/temp/lyme/Towns", layer="Towns", encoding = "UTF-8", verbose= FALSE)

检查 class:

class(ByTown)
#getting this result
[1] "SpatialPolygonsDataFrame"
attr(,"package")
[1] "sp"

然后我将所有因素转换为字符数据并再次使用 class 检查我是否还有一个 SpatialPolygonsDataFrame,我这样做了:

然后我将要合并的数据格式化为与原始数据相同的标题大小写:

townCount$City<-str_to_title(townCount$City)

然后我geo_join统计数据到空间多边形数据框:

ByTown<-geo_join(ByTown, townCount,"MCD_NAME", "City")

然后我设置调色板和 运行 映射:

pal = colorQuantile("PuOr",ByTown$count, n=5 )
map<-leaflet(ByTown) %>%
  addProviderTiles("CartoDB.Positron")%>%
  addPolygons(fillColor = ~pal(count),
            color = "#000000",
            stroke = TRUE,
            weight = 1,
            smoothFactor = 0.5,
            options(viewer = NULL))
map

我得到这个错误:

Error in derivePolygons(data, lng, lat, missing(lng), missing(lat), "addPolygons") : 
  addPolygons must be called with both lng and lat, or with neither.

我查看了坐标槽,里面有数据...我对这个错误感到困惑,并且没有在网上找到任何有用的答案。这是坐标槽中第一个多边形的头部:

head(nByTown@polygons[[1]]@Polygons[[1]]@coords )

           [,1]     [,2]
[1,] 1036519 916318.7
[2,] 1036039 916355.8
[3,] 1031757 916299.7
[4,] 1027474 916244.5
[5,] 1026709 916198.1
[6,] 1026826 916248.3

任何人都有这个问题,找出根本原因并解决它?

addPolygons 函数要求您定义纬度和经度列,或者它会尝试从您提供的数据中导出它们。

如果您没有指定 lat/lon 列,它会尝试找出它们是哪些。在你的情况下,它找不到它们。这主要是因为您的数据不是 lat/lon 格式。

因此,您需要转换数据以使用 lat/lon 投影,例如(未测试)

nByTown_latlon <- spTransform(nByTown, CRS("+proj=longlat +datum=WGS84"))

如果您没有在 leaflet() 调用中提供,请不要忘记在 addPolygons() 中添加 data = ... 变量名。 我收到了同样的错误并花了几个小时寻找解决方案:(.

有效:

leaflet() %>%
  addTiles() %>%
  addPolygons(ByTown)

和returns:

Error in derivePolygons(data, lng, lat, missing(lng), missing(lat), "addPolygons") : 
  addPolygons must be called with both lng and lat, or with neither.

这个有效:

leaflet() %>%
  addTiles() %>%
  addPolygons(data = ByTown)