![](/img/trans.png)
[英]Using the geosphere distm function on a data.table to calculate distances
[英]Distances between two points calculated with geosphere::distm are different than distances plotted with leaflet
我有兩個經緯度長的數據框。 DatasetA是一組位置。 數據集B是距數據集A 50英里(縱向)的一組位置。
我可以繪制兩個數據集而不會發生任何事件,如下面的代碼所示。 但是,當我計算數據集A和數據集B的點(最近的點)之間的距離時,會得到不同的距離:
> points$Distance2radius
[1] 44.13807 41.92467 39.39219 36.55992 33.44940
我很難理解為什么這些會有所不同。 我假設在distm中使用Haversine公式將說明對距離計算的任何球形影響。
任何幫助,將不勝感激。
library(leaflet)
library(geosphere)
### Make a dataframe of some test points ###
## Center of the US
dc.lat <- c(38.0000)
dc.long <- c(-97.0000)
## Make the data frame
lats <- c(dc.lat - 10, dc.lat - 5, dc.lat, 5 + dc.lat, 10 + dc.lat)
points <- data.frame(cbind(dc.long, lats))
names(points) <- c("long" , "lat")
coordinates(points) <- ~ long + lat
## The radius we are interested in, in miles
radius <- 50
## Add points that are the radius miles away from the center
points.at.radius <- data.frame(points)
#points$lat <- points$lat + radius/110.54
points.at.radius$long <- points$long + radius / 69.2
coordinates(points.at.radius) <- ~ long + lat
## Get distances with distm
distances <- distm (points, points.at.radius,
fun = distHaversine) / 1609
# Find the closest pint and add this distance to the data set
points$Distance2radius <-
apply(distances , 1, min)
# Plot these points and the points that are 50 miles away
m <- leaflet() %>%
addTiles() %>% # Add default OpenStreetMap map tiles
addCircleMarkers(data = points,
points$long,
points$lat,
color = "red") %>%
addPolygons(
data = gBuffer(
points,
width = radius / 69.2,
joinStyle = "ROUND",
byid = FALSE
),
color = "gray70",
group = "IWER area"
) %>%
addMarkers(data = points.at.radius,
points.at.radius$long,
points.at.radius$lat) %>% addPopups(
points$long,
points$lat,
47.597131,
points$Distance2radius,
options = popupOptions(closeButton = FALSE)
)
m # Print the map
使用geobuffer
非常簡單。
# Load libraries.
library(leaflet)
library(geosphere)
library(geobuffer)
# Set coordinates for center points.
coordinates <- data.frame(lon = -97,
lat = seq(28, 48, 5))
# Create SpatialPoints in the WGS84 spatial reference system,
# a.k.a. unprojected lon/lat.
points <- SpatialPoints(coords = coordinates,
proj4string = CRS("+init=epsg:4326"))
# Set radius as 50 miles.
radius <- 50 * 1609
# Created SpatialPolygons in the shape of an octagon.
buffered_points <- geobuffer::geobuffer_pts(xy = points,
dist_m = radius,
step_dg = 360 / 8)
> distm(points@coords[1,],
coordinates(buffered_points@polygons[[1]]@Polygons[[1]])) / 1609
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9]
[1,] 50 50 50 50 50 50 50 50 50
您會發現不僅對於SpatialPolygon#1,對於其他三個對象都是如此。
leaflet() %>%
addTiles() %>%
addCircleMarkers(data = points,
color = "red") %>%
addPolygons(
data = buffered_points,
color = "gray70"
)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.