為了確保地址始終以相同的方式格式化(我將在另一個 VBA 子程式中使用),我嘗試將 google places API 與 VBA 創建的函式結合使用。目前,我能夠使查詢正常作業(在瀏覽器中),但我無法從創建的函式中獲得我想要的結果。
正在運行的 API 如下(添加了臨時 API 密鑰)并添加了隨機地址: https ://maps.googleapis.com/maps/api/place/findplacefromtext/json?fields=formatted_address,name,rating,opening_hours ,geometry&input=Coendersweg 2&inputtype=textquery&key=AIzaSyDNZs0Dmc0xTQqxEjuU26A_f9IeNnA_78U
它給出了我想作為函式結果顯示的結果“Formatted_Address”。如果可以使結果地址的郵政編碼(9722 GE)格式為“9722GE”并且國家/地區“,Nederland”不顯示,那就更好了。
隨機地址的示例結果:
Coendersweg 2, 9722GE Groningen / [街道名稱,郵政編碼城市]
這是我到目前為止的 VBA 代碼:
Function FindAddress(address, APIKEY)
Dim strURL As String
strURL = "https://maps.googleapis.com/maps/api/place/findplacefromtext/" & _
"json?fields=formatted_address,name,rating,opening_hours,geometry&input=" _
& address & "&inputtype=textquery&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 FoundAddress As String
FoundAddress = (formatted_address)
FindAddress = FoundAddress
我也有來自https://github.com/VBA-tools/VBA-JSON的“JsonConverter.bas”作為我的 VBA 中的一個模塊。
大部分代碼是從以下 Youtube 視頻中借用的,我在其中做了一些調整以使用 Google Places API 而不是 Google Directions API: https ://www.youtube.com/watch?v=_P2lj4yHNu4
如果有人有解決方案以便該功能可以正常作業,并且能夠輸出和填充/格式化用作該功能的輸入的地址,將不勝感激。
uj5u.com熱心網友回復:
這是一個將回傳該formatted_address欄位的方法。如果您愿意,您可以回傳其他欄位——修改應該是顯而易見的。
請注意,我使用了早期系結,但如果您愿意,可以使用后期系結。
反對你的輸入,=>Coendersweg 2, 9722 GE Groningen, Netherlands
Option Explicit
Function getAddress(S As String)
Const API As String = "key=YOUR_API_KEY"
Const sURL1 As String = "https://maps.googleapis.com/maps/api/place/findplacefromtext/json?fields=formatted_address"
Const sURL2 As String = "input="
Const sURL3 As String = "inputtype=textquery"
Dim sAddr As String
Dim sURL() As String
Dim sLocation As String
Dim xhrRequest As XMLHTTP60
Dim strJSON As String, JSON As Object
sAddr = Replace(S, " ", " ")
'Many ways to create the URL to send
ReDim sURL(3)
sURL(0) = sURL1
sURL(1) = sURL2 & sAddr
sURL(2) = sURL3
sURL(3) = API
Set xhrRequest = New XMLHTTP60
With xhrRequest
.Open "Get", Join(sURL, "&"), False
.Send
strJSON = .ResponseText
End With
Set JSON = ParseJson(strJSON)
If Not JSON("status") = "OK" Then
MsgBox "Status message: " & JSON("status")
Exit Function
End If
'might need to check if more than one candidate is returned
getAddress = JSON("candidates")(1)("formatted_address")
End Function
如果您希望格式與顯示的不同,我建議您使用Placesapi 回傳place_id. 然后,您可以將該值輸入Place Details以回傳address_components并格式化您喜歡的地址。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/514471.html
上一篇:如何從資料框中的1開始
