PoshCode Archive  Artifact [d9620b6d00]

Artifact d9620b6d00ce7098648477deb47c03f012d2d52c21c3158a6ca9630e6ef76dec:

  • File Get-DistanceOnEarth.ps1 — part of check-in [0ba3a887f0] at 2018-06-10 13:12:51 on branch trunk — Uses the Haversine equation (you know you LOVE spherical geometry) to calculate distance between two points on the earth. (user: callias size: 1847)

# encoding: ascii
# api: powershell
# title: Get-DistanceOnEarth
# description: Uses the Haversine equation (you know you LOVE spherical geometry) to calculate distance between two points on the earth.
# version: 6378.1
# type: function
# author: callias
# license: CC0
# function: Get-DistanceOnEarth
# x-poshcode-id: 2591
# x-archived: 2016-05-28T20:41:42
# x-published: 2011-03-29T06:31:00
#
# The value of $R is set to the radius of the earth in miles; swap out comments to calculate in km.
# This function works especially well with output from a modified version of Jason Hofferle’s Google Geocoding script:
# http://www.hofferle.com/index.php/archives/48
#
function Get-DistanceOnEarth {
<#
.SYNOPSIS
  Calculates distance between points on the Earth.
.DESCRIPTION
  Implementation of the Haversine equation to calculate distance over the surface of a sphere.
.INPUTTYPE
  Pipeline object with the following parameters: LATITUDE1 LONGITUDE1 LATITUDE2 LONGITUDE2
#>
    Begin
    {
        $toRad = 0.0174532925 # radians in 1 degree
        $R = 3963.1676  # approx. radius of earth in milies
        #$R = 6378.1  # approx. radius of earth in km
    }
    
    Process
    {
        $lat1 = $_.LATITUDE1
        $lon1 = $_.LONGITUDE1
        $lat2 = $_.LATITUDE2
        $lon2 = $_.LONGITUDE2
        $dLat = ($lat2 - $lat1) * $toRad
        $dLon = ($lon2 - $lon1) * $toRad
        $a = ( ( ([Math]::Sin($dLat/2)) * ([Math]::Sin($dLat/2)) ) + ([Math]::Cos($lat1 * $toRad) * [Math]::Cos($lat2 * $toRad) * ( ([Math]::Sin($dLon/2)) * ([Math]::Sin($dLon/2)) )))
        $c = 2 * [Math]::Atan2([Math]::Sqrt($a), [Math]::Sqrt(1-$a))
        $d = $R * $c
        $d = [Math]::Round($d,3)
        $_ | Add-Member -MemberType NoteProperty -Name Distance -Value $d
        Write-Output $_
    }
}