Google API距离matrix返回错误的JSON导致VBA

希望有人能把我指向正确的方向。 我有一个从Excel调用的VBA函数来调用从一个邮政编码到另一个邮政编码的距离。 这工作正常,直到现在。

只需要计算荷兰的距离,但不能将查询string限制在一个国家。 现在我有一个邮政编码2151 KD,我用它在我的查询string中作为从或到邮政编码。 喜欢:

http://maps.googleapis.com/maps/api/distancematrix/json?origins=1251KD&destinations=1211LW&mode=car&sensor=false

(我删除了数字和字母之间的空格)。

当我在浏览器中时,这工作正常。 显示正确的位置和距离。 (Destionation或起源)。

这个查询string是使用这个VBA函数在代码中生成的:

Function GetDistance(fromZip As String, toZip As String) As Integer Dim Uri As String: Uri = "http://maps.googleapis.com/maps/api/distancematrix/json?origins={0}&destinations={1}&mode=car&sensor=false" Dim xmlHttp As Object: Set xmlHttp = CreateObject("MSXML2.ServerXMLHTTP.6.0") Dim Json As Object Dim distance As Double: distance = 0 Uri = Replace(Uri, "{0}", fromZip) Uri = Replace(Uri, "{1}", toZip) With xmlHttp .Open "GET", Uri, False .setRequestHeader "Content-Type", "text/xml" .send End With 'Debug.Print (Uri) Set Json = JsonConverter.ParseJson(xmlHttp.ResponseText) 'Top-level status OK If Json("status") = "OK" Then 'Elementstatus If Json("rows")(1)("elements")(1)("status") = "OK" Then distance = CLng(Json("rows")(1)("elements")(1)("distance")("value")) / 1000 Else distance = -2 End If Else distance = -1 End If If fromZip = "1251KD" Or toZip = "1251KD" Then Debug.Print (xmlHttp.ResponseText) Debug.Print (Uri) End If If IsObject(xmlHttp) Then Set xmlHttp = Nothing End If If IsObject(Json) Then Set Json = Nothing End If GetDistance = Round(distance, 0) 

结束function

但结果是不同的。 公元1251年,现在在美国的一个位置。 而且没有距离计算。

从VBA代码调用时的结果:

 { "destination_addresses" : [ "1211 LW Hilversum, Netherlands" ], "origin_addresses" : [ "NE 1251, Osceola, MO 64776, USA" ], "rows" : [ { "elements" : [ { "status" : "ZERO_RESULTS" } ] } ], "status" : "OK" } 

结果从浏览器直接调用时:

 { destination_addresses: [ "1211 LW Hilversum, Nederland" ], origin_addresses: [ "1251 KD Laren, Nederland" ], rows: [ { elements: [ { distance: { text: "6,9 km", value: 6878 }, duration: { text: "14 min.", value: 810 }, status: "OK" } ] } ], status: "OK" } 

到目前为止,我还没有弄清楚如何解决这个问题。 查询string正在工作,当我把它粘贴到浏览器的地址栏,但从VBA调用时结果是无效的。 到目前为止,只有这个特定的邮政编码1251 KD。

有没有人拥有?

对不起,我不能重现你的错误 – 代码工作得很好。

但是,如果您只需要荷兰的结果,为什么不把国家添加到查询string?

对于你的代码,这意味着什么

 Uri = Replace(Uri, "{0}", fromZip & ",Netherlands") Uri = Replace(Uri, "{1}", toZip & ",Netherlands")