簡體   English   中英

如何計算形狀文件中質心到多邊形的距離? 電阻

[英]How to calculate the distance of a centroid to a polygon in a shape file? R

我有這個,我正在嘗試使用gDistance來計算每個質心與巴格達市之間的距離。 我正在嘗試這樣做:地圖

gDistance(districts_centroids, districts@data$ADM3NAME %in% c("Baghdad"), byid=TRUE)

其中district_centroidsFormal Class SpatialPoints ,而districts@data...基本上是shp文件中的巴格達市。

我收到一條錯誤消息,內容如下:

(function (classes, fdef, mtable) 中的錯誤:無法找到用於簽名 '"logical"' 的函數 'is.projected' 的繼承方法另外:警告消息:在 RGEOSDistanceFunc(spgeom1, spgeom2, byid, "rgeos_distance" ) : 空間對象 1 未投影;GEOS 需要平面坐標

我對 R 完全陌生,我真的不知道發生了什么。

任何幫助,將不勝感激

謝謝!

這是一個很好的問題。 看了一些東西后,決定回答這個問題的最好方法是使用simple feature objects而不是空間對象。

有問題的地圖看起來很熟悉。 我使用了IRQ_2_sf.rds地圖,它可能與上面使用和顯示的地圖相同。 還有其他替代方法可以解決這個問題。 Jupyter Lab 是使用的 IDE。

使用 Google API 和geocode功能,檢索了巴格達的坐標。

baghdad <- geocode("Baghdad, Iraq", source = c("google") )

A tibble: 1 × 2
 lon         lat
<dbl>       <dbl>
44.36607    33.31524

然后使用sf函數創建sf column object

baghdad.sfg <- st_point(c(lon, lat), dim = "XY")
baghdad.sfc <- st_sfc(baghdad.sfg, crs = 4326)

然后,使用名為 iraq 的 sf 地圖創建centroids 注意:警告消息 - st_centroid 沒有為經度/緯度數據提供正確的質心。 對於這個答案,質心將足夠接近。

iraq.c <- st_centroid(iraq)

從每個centroid巴格達的距離以公里為單位確定。

head(dist <- data.frame(c(st_distance(iraq.c$geom[], baghdad.sfc)/1000)))

Units: [m]
[1]  28.63250  59.61553 215.43354 323.06418 259.14509 113.55356

然后創建一個包含名稱、 centroid幾何和距離值的日期框架。 需要一些清潔和綁定。

distance <- c(dist$c.st_distance.iraq.c.geom....baghdad.sfc..1000.)

x <- distance[]
d_Bdad_Km <- as.numeric(str_extract(x, "[0-9]*.[0-9]."))

iraq2 <- iraq[-c(5, 8,9,10,11,12,13)] 
df_dist <- cbind(iraq2, d_Bdad_Km)      # df as desired

然后輸出被plotted

plot(iraq$geom)
plot(iraq.c$geom, add = TRUE, col = "red")
plot(baghdad.sfc, add = TRUE, pch = 19, col = "blue")

請詢問是否有任何后續問題。 可以在此鏈接中查看該圖

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM