Calculate distance between 2 GPS coordinates

前端 未结 29 3574
青春惊慌失措
青春惊慌失措 2020-11-21 23:34

How do I calculate distance between two GPS coordinates (using latitude and longitude)?

29条回答
  •  一个人的身影
    2020-11-22 00:05

    I needed to implement this in PowerShell, hope it can help someone else. Some notes about this method

    1. Don't split any of the lines or the calculation will be wrong
    2. To calculate in KM remove the * 1000 in the calculation of $distance
    3. Change $earthsRadius = 3963.19059 and remove * 1000 in the calculation of $distance the to calulate the distance in miles
    4. I'm using Haversine, as other posts have pointed out Vincenty's formulae is much more accurate

      Function MetresDistanceBetweenTwoGPSCoordinates($latitude1, $longitude1, $latitude2, $longitude2)  
      {  
        $Rad = ([math]::PI / 180);  
      
        $earthsRadius = 6378.1370 # Earth's Radius in KM  
        $dLat = ($latitude2 - $latitude1) * $Rad  
        $dLon = ($longitude2 - $longitude1) * $Rad  
        $latitude1 = $latitude1 * $Rad  
        $latitude2 = $latitude2 * $Rad  
      
        $a = [math]::Sin($dLat / 2) * [math]::Sin($dLat / 2) + [math]::Sin($dLon / 2) * [math]::Sin($dLon / 2) * [math]::Cos($latitude1) * [math]::Cos($latitude2)  
        $c = 2 * [math]::ATan2([math]::Sqrt($a), [math]::Sqrt(1-$a))  
      
        $distance = [math]::Round($earthsRadius * $c * 1000, 0) #Multiple by 1000 to get metres  
      
        Return $distance  
      }
      

提交回复
热议问题