Imports System.IO
Imports System.Net
Imports System.Web
Imports System.Text

Public Class cGoogleAPI

    Public Shared APIKEY_distancematrix As String = "AIzaSyAyXX4aYtoE_v0tXhmuiApV6Qo2Ka2ObJY"


    Public Shared Sub test()
        Dim duration = ""
        Dim distance = ""
        Dim distanceSek = ""

        GoogleDistance("A 4975 Suben 100", "A st. marienkirchen Hackenbuch 27", duration, distanceSek, distance)
        MsgBox(duration)
        MsgBox(distance)

    End Sub
    Public Shared Sub GoogleDistance(origin As String, destination As String, ByRef duration As Object, ByRef distance As Object, Optional lkw As Boolean = True)
        Try

            Dim url As String = "https://maps.googleapis.com/maps/api/distancematrix/xml?origins=" & HttpUtility.UrlEncode(origin) & "&destinations=" + HttpUtility.UrlEncode(destination) & "&key=" & APIKEY_distancematrix
            ' MsgBox(url)
            Dim request As WebRequest = WebRequest.Create(url)
            Dim response As WebResponse = CType(request.GetResponse(), HttpWebResponse)
            Dim reader As StreamReader = New StreamReader(response.GetResponseStream(), Encoding.UTF8)
            Dim dsResult As DataSet = New DataSet()
            dsResult.ReadXml(reader)

            If lkw Then
                Dim durationSek As Integer = 0
                If dsResult.Tables("duration") Is Nothing Then
                    durationSek = 0
                Else
                    durationSek = dsResult.Tables("duration").Rows(0)("value").ToString()
                End If
                If IsNumeric(durationSek) Then
                    durationSek = durationSek * 1.5 ' Bei LKW wird die Zeit um diesen Faktor hochgerechnet
                    Dim iSpan As TimeSpan = TimeSpan.FromSeconds(durationSek)
                    duration = iSpan.Hours.ToString.PadLeft(2, "0"c) & " Stunden " & iSpan.Minutes.ToString.PadLeft(2, "0"c) & " Minuten"
                End If
            Else
                If dsResult.Tables("duration") Is Nothing Then
                    duration = ""
                Else
                    duration = dsResult.Tables("duration").Rows(0)("text").ToString()
                End If
            End If


            If dsResult.Tables("distance") Is Nothing Then
                distance = ""
            Else
                distance = dsResult.Tables("distance").Rows(0)("text").ToString()
            End If


        Catch ex As Exception
            MsgBox(ex.Message & ex.StackTrace)
        End Try
    End Sub
End Class
