Calculate distance between two long lat coordinate

2020-06-25 01:10发布

问题:

I want to calculate the distance between several GPS points. I tried

distm(c(lon1,lat1), c(lon2,lat2), fun = distHaversine)

which worked for one point, but not for the columns in my data frame.

So I tried as recommended here:

Calculate distance between 2 lat longs

But I do get different results for these two calculations:

df <- read.table(sep=",", col.names=c("lat1", "lon1", "lat2", "lon2"),text="
7.348687,53.36575,7.348940,53.36507 
7.348940, 53.36507,7.350939,53.36484")


# as recommended in the link above
distHaversine(df[,2:1], df[,4:3])

[1]  80.18433 223.97181

# with distm
distm(c(7.348687,53.36575), c(7.348940,53.36507), fun = distHaversine)

         [,1]
[1,] 77.54033

distm(c(7.348940, 53.36507), c(7.350939,53.36484), fun = distHaversine)

         [,1]
 [1,] 135.2317

So how can I calculate the correct distances (which is distm(c(lon1,lat1), c(lon2,lat2), fun = distHaversine)) between two GPS points in the columns of my data frame? I double-checked with so distances that I know I get the right distances this way.

Thanks in advance.

回答1:

Given that the output you want to store in the new column is this:

77.54033 135.23165

Try this

df$distance<-distHaversine(df[,1:2], df[,3:4])

Which should return

> df
      lat1     lon1     lat2     lon2  distance
1 7.348687 53.36575 7.348940 53.36507  77.54033
2 7.348940 53.36507 7.350939 53.36484 135.23165


回答2:

What exactly is the question? Don't you already have all the distances you need with distHaversine()?

Do you want to add the distance as column in the dataframe? Here you go:

f$dist <- distm(x = df[, c('lon1', 'lat1')], 
                y = df[, c('lon2', 'lat2')],
                fun = distHaversine
                )


回答3:

I found another solution for the problem

for (i in 1:2) {

  a<-df$lon1[i]
  b<-df$lat1[i]
  c<-df$lon2[i]
  d<-df$lat2[i]

  df$distance[i]<-distm(c(a,b),c(c,d), fun = distHaversine)
  }

write.xlsx(df, file = "C:/Users/distances.xlsx")


标签: r distance