Jump to content
  • Data Function to Compute Distance (in km & mi) between two points that have lat/long


    Table of Contents


    Background

    Spotfire can automatically show the distance between points on a map (as shown in the image below).  Changing the selector type to a radius displays the distance from the center of the circle to the diameter.  Use the Properties menu to configure whether the display shows Miles or Kilometers.

    distance.png.cadad9ca1e31ba7ef8eba87f0a9bc266.png

    Use Case

    You might require a more accurate computation than a manual visual measure, and you want to bring the result into a Spotfire data table.  You can obtain such a measure by using a TERR data function. 

    The attached file (distancebtwn2pts.7z) contains a data function file (distance.sfd) and a dxp file (distance.dxp) that uses the data function to compute the distance between two marked points.  Two columns (X and Y = Long and Lat) are passed into the data function and only the first 2 points are used in the distance calculation.  Both the Kilometers and Miles are computed and returned in a table.

    Inputs:  Longitude_Column, Latitude_Column

    Output:  Table (containing a Kilometers distance & Miles distance)

    Data Function Code

    # Inputs: 
    #   longitude : column with logitude values 
    #   latitude : column with latitude values  
    # Outputs: 
    #   myout : table with distance results (in Miles and Kilometers)
    
    long1 = longitude[1]   
    long2 = longitude[2]   
    lat1 = latitude[1]   
    lat2 = latitude[2]      
    # Calculate distance in kilometers between two points   
    earth.dist <- function (long1, lat1, long2, lat2)
       {
         rad <- pi/180
         a1 <- lat1 * rad
         a2 <- long1 * rad
         b1 <- lat2 * rad
         b2 <- long2 * rad
         dlon <- b2 - a2
         dlat <- b1 - a1
         a <- (sin(dlat/2))^2 + cos(a1) * cos(b1) * (sin(dlon/2))^2
         c <- 2 * atan2(sqrt(a), sqrt(1 - a))
         R <- 6378.145
         d <- R * c     
         return(d)
       }      
     dist_km <- earth.dist(long1,lat1,long2,lat2)   
     dist_mi <- dist_km / 1.609344      
     myout <- data.frame("dist_km"=dist_km,"dist_mi"=dist_mi)
     

    Attachments

    Download From Resources.

    distancebtw2pts.7z


    User Feedback

    Recommended Comments

    There are no comments to display.


×
×
  • Create New...