计算两个纬度之间的距离 [英] Calculate distance between 2 lat longs

查看:127
本文介绍了计算两个纬度之间的距离的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的数据帧lat1,long1 ... lat2,long2中有4列.我需要计算这些对之间的距离.我正在尝试使用Distm函数.

I have 4 columns in my data frame lat1,long1...lat2,long2. I need to calculate distance between these pairs. I am trying to use Distm function.

当我尝试使用distm (c(mydata2$lst_upd_longitude,mydata2$lst_upd_latitude), c(mydata2$long,mydata2$lat), fun = distHaversine)

R引发错误".pointsToMatrix(x)中的错误:向量的长度错误,应为2" 现在,我正在使用下面的代码来计算每个点的距离.但是我相信应该有一个更好的解决方案.此外,这段代码会消耗大量时间.

R throws up an error "Error in .pointsToMatrix(x) : Wrong length for a vector, should be 2" For now I am using the below code to calculate distance for every point. But I am sure there should be a better solution. Also this code consumes lot of time.

for( i in 1:nrow(mydata2)){
  mydata2$distance[i] <- distm (c(mydata2$lst_upd_longitude[i],mydata2$lst_upd_latitude[i]), 
                                c( mydata2$long[i],mydata2$lat[i]), 
                                fun = distHaversine)}

推荐答案

尝试

df <- read.table(sep=",", col.names=c("lat1", "lon1", "lat2", "lon2"), text="
52,4,52,13 
39,116,52,13")
library(geosphere)
distHaversine(df[, 2:1], df[, 4:3]) / 1000 # Haversine distance in km

这篇关于计算两个纬度之间的距离的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆