Programación

Visual Basic .Net

Cálculo de distancia entre coordenadas

Public Class MathFx

    ''' <summary>
    ''' Cambio de grados a radianes
    ''' </summary>
    ''' <param name=value">Valor a pasar a radianes</param>"
    ''' <returns>Radianes</returns>
    Public Shared Function toRad(ByVal value As Double) As Double
        Return value * Math.PI / 180
    End Function



    ''' <summary>
    ''' Distancia en metros entre coordenadas
    ''' </summary>
    ''' <param name=lat1">Latitud de la primera coordenada</param>"
    ''' <param name=lng1">Longitud de la primera coordenada</param>"
    ''' <param name=lat2">Latitud de la segunda coordenada</param>"
    ''' <param name=lng2">Longitud de la segunda coordenada</param>"
    ''' <returns>Distancia en metros</returns>
    Public Shared Function distanceBetween(ByVal lat1 As Double, ByVal lng1 As Double,
                                             ByVal lat2 As Double, ByVal lng2 As Double
                                             ) As Double
        Dim a As Double, b As Double
        Dim r As Double = 6371 * 1000 'Radio de la tierra para obtener metros
        Dim dLat As Double = toRad(lat2 - lat1)
        Dim dLng As Double = toRad(lng2 - lng1)

        a = Math.Pow(Math.Sin(dLat / 2), 2) _
            + (
                Math.Pow(Math.Cos(toRad(lat2)), 2) _
                    * Math.Pow(Math.Sin((dLng / 2)), 2)
              )

        b = 2 * Math.Atan2(Math.Sqrt(a), Math.Sqrt(1 - a))

        Return r * b

    End Function


End Class