PoshCode Logo PowerShell Code Repository

Get-DistanceOnEarth by callias 6 years ago
embed code: <script type="text/javascript" src="http://PoshCode.org/embed/2591"></script>download | new post

Uses the Haversine equation (you know you LOVE spherical geometry) to calculate distance between two points on the earth.
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

  1. function Get-DistanceOnEarth {
  2. <#
  3. .SYNOPSIS
  4.   Calculates distance between points on the Earth.
  5. .DESCRIPTION
  6.   Implementation of the Haversine equation to calculate distance over the surface of a sphere.
  7. .INPUTTYPE
  8.   Pipeline object with the following parameters: LATITUDE1 LONGITUDE1 LATITUDE2 LONGITUDE2
  9. #>
  10.     Begin
  11.     {
  12.         $toRad = 0.0174532925 # radians in 1 degree
  13.         $R = 3963.1676  # approx. radius of earth in milies
  14.         #$R = 6378.1  # approx. radius of earth in km
  15.     }
  16.    
  17.     Process
  18.     {
  19.         $lat1 = $_.LATITUDE1
  20.         $lon1 = $_.LONGITUDE1
  21.         $lat2 = $_.LATITUDE2
  22.         $lon2 = $_.LONGITUDE2
  23.         $dLat = ($lat2 - $lat1) * $toRad
  24.         $dLon = ($lon2 - $lon1) * $toRad
  25.         $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)) )))
  26.         $c = 2 * [Math]::Atan2([Math]::Sqrt($a), [Math]::Sqrt(1-$a))
  27.         $d = $R * $c
  28.         $d = [Math]::Round($d,3)
  29.         $_ | Add-Member -MemberType NoteProperty -Name Distance -Value $d
  30.         Write-Output $_
  31.     }
  32. }

Submit a correction or amendment below (
click here to make a fresh posting)
After submitting an amendment, you'll be able to view the differences between the old and new posts easily.

Syntax highlighting:


Remember me