Function DriveDistanceGoogleMaps(From As String, Dest As String, GoogleMapsKey As String, OptimizeOpt As Integer) As String
Dim oHttpReq As MSXML2.XMLHTTP
Dim bodytxt, Temps_Texte, distance As String
Dim temps As Long
Dim z As Integer
Set oHttpReq = New MSXML2.XMLHTTP
From = Replace(From, " ", "+")
Dest = Replace(Dest, " ", "+")
Select Case OptimizeOpt
Case 0
OptimizeOption = ""
Case 1
OptimizeOption = "&avoid=tolls"
Case 2
OptimizeOption = "&avoid=highways"
Case 3
OptimizeOption = "&avoid=ferries"
Case 4
OptimizeOption = "&avoid=indoor"
Case Else
OptimizeOption = ""
End Select
oHttpReq.Open "get", "https://maps.googleapis.com/maps/api/distancematrix/xml?origins=" & From & "&destinations=" & Dest & "&units=metric" & OptimizeOption & "&mode=driving&key=" & GoogleMapsKey, "false"
oHttpReq.send
bodytxt = oHttpReq.responseText
bodytxt = Right(bodytxt, Len(bodytxt) - InStr(1, bodytxt, "<text>") - 5)
If InStr(1, bodytxt, "</text>") <> 0 Then Temps_Texte = Left(bodytxt, InStr(1, bodytxt, "</text>") - 1)
If Temps_Texte <> "" Then
Temps_Texte = Replace(Temps_Texte, " semaines", "w")
Temps_Texte = Replace(Temps_Texte, " semaine", "w")
Temps_Texte = Replace(Temps_Texte, " jours", "j")
Temps_Texte = Replace(Temps_Texte, " jour", "j")
Temps_Texte = Replace(Temps_Texte, " heures", "h")
Temps_Texte = Replace(Temps_Texte, " heure", "h")
Temps_Texte = Replace(Temps_Texte, " minutes", "m")
Temps_Texte = Replace(Temps_Texte, " minute", "m")
Temps_Texte = Replace(Temps_Texte, " secondes", "s")
Temps_Texte = Replace(Temps_Texte, " seconde", "s")
Hours = Split(Temps_Texte, " ")
z = 0
On Error GoTo fin
If Right(Hours(z), 1) = "w" Then temps = temps + Val(Hours(z)) * 7 * 24 * 60 * 60: z = z + 1
If Right(Hours(z), 1) = "d" Then temps = temps + Val(Hours(z)) * 24 * 60 * 60: z = z + 1
If Right(Hours(z), 1) = "h" Then temps = temps + Val(Hours(z)) * 60 * 60: z = z + 1
If Right(Hours(z), 1) = "m" Then temps = temps + Val(Hours(z)) * 60: z = z + 1
If Right(Hours(z), 1) = "s" Then temps = temps + Val(Hours(z)): z = z + 1
fin:
On Error GoTo 0
End If
bodytxt = Right(bodytxt, Len(bodytxt) - InStr(1, bodytxt, "<text>") - 5)
If InStr(1, bodytxt, "</text>") <> 0 Then distance = Left(bodytxt, InStr(1, bodytxt, "</text>") - 1)
distance = Replace(distance, ",", ".")
Temps_Texte = ""
j = 1
While j < Len(distance) + 1
If ((Asc(Mid(distance, j, 1)) > 47) And (Asc(Mid(distance, j, 1)) < 58)) Or (Asc(Mid(distance, j, 1)) = 44) Or (Asc(Mid(distance, j, 1)) = 46) Then
Temps_Texte = Temps_Texte & Mid(distance, j, 1)
End If
j = j + 1
Wend
If InStr(1, bodytxt, "m") <> 0 And InStr(1, bodytxt, "km") = 0 Then
If Temps_Texte = "1" Then
temps = "0"
Temps_Texte = 0
End If
Temps_Texte = str(CDbl(Temps_Texte) / 1000)
End If
DriveDistanceGoogleMaps = Temps_Texte
travelDuration = CStr(temps)
Set oHttpReq = Nothing
End Function