使用 Google API in Excel (VBA) 计算地址之间的距离
Calculating distance between adresses using Google API in Excel (VBA)
我正在写我的硕士论文,真的需要你的帮助来计算一些距离。
为了计算几个地址(~10k 对)之间的距离,我真的很难处理我在网上找到的一些代码。我尝试了来自两个网站的两种不同的代码,它们都给我一个错误。
我已经创建了自己的 Google API,并激活了计费(使用 URL 测试对我来说确实有效)并尝试了其他论坛的一些建议。
1.方法
发现于:https://analystcave.com/excel-calculate-distances-between-addresses/
代码
'Calculate Google Maps distance between two addresses
Public Function GetDistance(start As String, dest As String)
Dim firstVal As String, secondVal As String, lastVal As String
firstVal = "http://maps.googleapis.com/maps/api/distancematrix/json?origins="
secondVal = "&destinations="
lastVal = "&mode=car&language=pl&sensor=false&key=YOUR_KEY"
Set objHTTP = CreateObject("MSXML2.ServerXMLHTTP")
URL = firstVal & Replace(start, " ", "+") & secondVal & Replace(dest, " ", "+") & lastVal
objHTTP.Open "GET", URL, False
objHTTP.setRequestHeader "User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)"
objHTTP.send ("")
If InStr(objHTTP.responseText, """distance"" : {") = 0 Then GoTo ErrorHandl
Set regex = CreateObject("VBScript.RegExp"): regex.Pattern = """value"".*?([0-9]+)": regex.Global = False
Set matches = regex.Execute(objHTTP.responseText)
tmpVal = Replace(matches(0).SubMatches(0), ".", Application.International(xlListSeparator))
GetDistance = CDbl(tmpVal)
Exit Function
ErrorHandl:
GetDistance = -1
End Function
每次我应用公式时,我都会收到“-1”,即错误消息。
2。方法
发现于:https://syntaxbytetutorials.com/excel-function-to-calculate-distance-using-google-maps-api-with-vba/
这里我也按照作者的建议添加了VBA-JSON和激活的引用
代码
' Returns the number of seconds it would take to get from one place to another
Function TRAVELDISTANCE(origin, destination, apikey)
Dim strUrl As String
strUrl = "https://maps.googleapis.com/maps/api/directions/json?origin=" & origin & "&destination=" & destination & "&key=" & apikey
Set httpReq = CreateObject("MSXML2.XMLHTTP")
With httpReq
.Open "GET", strUrl, False
.Send
End With
Dim response As String
response = httpReq.ResponseText
Dim parsed As Dictionary
Set parsed = JsonConverter.ParseJson(response)
Dim meters As Integer
Dim leg As Dictionary
For Each leg In parsed("routes")(1)("legs")
meters = meters + leg("distance")("value")
Next leg
TRAVELDISTANCE = meters
End Function
这里,由于行中的错误,函数实际上没有编译
strUrl = "https://maps.googleapis.com/maps/api/directions/json?origin=" & origin & "&destination=" & destination & "&key=" & apikey
它 returns "Expected: end of statement" 错误。
我完全迷路了,如果你们中的任何人能提供一些帮助,我将不胜感激。
最好的,
菲利克斯
就第二种方法而言,根据 this,URL 应该类似于以下示例:
所以在你的情况下,如果你有一个名为 origin
的变量,另一个名为 destination
和第三个名为 apikey
的变量,则应该构建 URL像这样:
strUrl ="https://maps.googleapis.com/maps/api/directions/json?origin=" & origin & "&destination=" & destination & "&key=" & apikey
函数必须这样调用,例如:
call TRAVELDISTANCE("Disneyland", "Universal+Studios+Hollywood", "xxxxx")
我想发生的事情是,在您找到原始代码的网站上,&
字符在其 HTML 版本中被解析为:&
。但是,这会在 VBA.
中产生错误
因此,在复制和粘贴内容之前,您需要了解其工作原理。
要组合字符串,通常适用以下规则:
finalString= String1 & String2 & "String3" & "String4" & ..... 'depending on whether your strings are stored in variables or not.
我正在写我的硕士论文,真的需要你的帮助来计算一些距离。
为了计算几个地址(~10k 对)之间的距离,我真的很难处理我在网上找到的一些代码。我尝试了来自两个网站的两种不同的代码,它们都给我一个错误。
我已经创建了自己的 Google API,并激活了计费(使用 URL 测试对我来说确实有效)并尝试了其他论坛的一些建议。
1.方法 发现于:https://analystcave.com/excel-calculate-distances-between-addresses/
代码
'Calculate Google Maps distance between two addresses
Public Function GetDistance(start As String, dest As String)
Dim firstVal As String, secondVal As String, lastVal As String
firstVal = "http://maps.googleapis.com/maps/api/distancematrix/json?origins="
secondVal = "&destinations="
lastVal = "&mode=car&language=pl&sensor=false&key=YOUR_KEY"
Set objHTTP = CreateObject("MSXML2.ServerXMLHTTP")
URL = firstVal & Replace(start, " ", "+") & secondVal & Replace(dest, " ", "+") & lastVal
objHTTP.Open "GET", URL, False
objHTTP.setRequestHeader "User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)"
objHTTP.send ("")
If InStr(objHTTP.responseText, """distance"" : {") = 0 Then GoTo ErrorHandl
Set regex = CreateObject("VBScript.RegExp"): regex.Pattern = """value"".*?([0-9]+)": regex.Global = False
Set matches = regex.Execute(objHTTP.responseText)
tmpVal = Replace(matches(0).SubMatches(0), ".", Application.International(xlListSeparator))
GetDistance = CDbl(tmpVal)
Exit Function
ErrorHandl:
GetDistance = -1
End Function
每次我应用公式时,我都会收到“-1”,即错误消息。
2。方法 发现于:https://syntaxbytetutorials.com/excel-function-to-calculate-distance-using-google-maps-api-with-vba/
这里我也按照作者的建议添加了VBA-JSON和激活的引用
代码
' Returns the number of seconds it would take to get from one place to another
Function TRAVELDISTANCE(origin, destination, apikey)
Dim strUrl As String
strUrl = "https://maps.googleapis.com/maps/api/directions/json?origin=" & origin & "&destination=" & destination & "&key=" & apikey
Set httpReq = CreateObject("MSXML2.XMLHTTP")
With httpReq
.Open "GET", strUrl, False
.Send
End With
Dim response As String
response = httpReq.ResponseText
Dim parsed As Dictionary
Set parsed = JsonConverter.ParseJson(response)
Dim meters As Integer
Dim leg As Dictionary
For Each leg In parsed("routes")(1)("legs")
meters = meters + leg("distance")("value")
Next leg
TRAVELDISTANCE = meters
End Function
这里,由于行中的错误,函数实际上没有编译
strUrl = "https://maps.googleapis.com/maps/api/directions/json?origin=" & origin & "&destination=" & destination & "&key=" & apikey
它 returns "Expected: end of statement" 错误。
我完全迷路了,如果你们中的任何人能提供一些帮助,我将不胜感激。
最好的, 菲利克斯
就第二种方法而言,根据 this,URL 应该类似于以下示例:
所以在你的情况下,如果你有一个名为 origin
的变量,另一个名为 destination
和第三个名为 apikey
的变量,则应该构建 URL像这样:
strUrl ="https://maps.googleapis.com/maps/api/directions/json?origin=" & origin & "&destination=" & destination & "&key=" & apikey
函数必须这样调用,例如:
call TRAVELDISTANCE("Disneyland", "Universal+Studios+Hollywood", "xxxxx")
我想发生的事情是,在您找到原始代码的网站上,&
字符在其 HTML 版本中被解析为:&
。但是,这会在 VBA.
因此,在复制和粘贴内容之前,您需要了解其工作原理。
要组合字符串,通常适用以下规则:
finalString= String1 & String2 & "String3" & "String4" & ..... 'depending on whether your strings are stored in variables or not.