【问题标题】:Calculate distance between 2 lat longs计算 2 lat longs 之间的距离
【发布时间】:2016-06-15 01:55:33
【问题描述】:

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

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

R 抛出错误“.pointsToMatrix(x) 中的错误:向量的长度错误,应为 2” 现在我正在使用下面的代码来计算每个点的距离。但我相信应该有更好的解决方案。这段代码也很耗时。

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)}

【问题讨论】:

    标签: r geospatial geo haversine


    【解决方案1】:

    试试

    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
    

    【讨论】:

    • 我的经纬度数据已经在数据框中。当我直接应用 distm 函数时出现错误 Error in .pointsToMatrix(x) : Wrong length for a vector, should be 2
    • 我的经纬度数据也在数据框中。当应用 distHaverine 时,我没有收到错误,但对之间的距离。
    【解决方案2】:

    请尝试以下脚本代码:

     function getDistanceFromLatLonInKm(lat1,lon1,lat2,lon2) {
     var R = 6371; // Radius of the earth in km
     var dLat = deg2rad(lat2-lat1);  // deg2rad below
     var dLon = deg2rad(lon2-lon1); 
     var a = 
     Math.sin(dLat/2) * Math.sin(dLat/2) +
     Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) * 
     Math.sin(dLon/2) * Math.sin(dLon/2)
     ; 
     var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); 
     var d = R * c; // Distance in km
     return d;
     }
    
    function deg2rad(deg) {
     return deg * (Math.PI/180)
    }
    

    更多详情请点击以下链接:

    Calculate distance between two latitude-longitude points? (Haversine formula)

    【讨论】:

      猜你喜欢
      • 2012-04-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-05
      • 1970-01-01
      • 2018-05-20
      • 1970-01-01
      相关资源
      最近更新 更多