从地址获取GPS坐标的代码(VB / VB.Net / VBA / VBScript)

问题描述 投票:2回答:2

我相信Google API允许您获取给定地址的坐标。但是,我发现的大多数(或我应该说全部)示例都不适合vb。通常,这是一些javascript示例,让我感到困惑。

这里有一些使用地理编码服务的代码。这很好。只是我想直接自己查询Google地图。

Public Function fgGetLatAndLongUsingAddress(sAddress As String) As String

    'This function works best with a complete address including the zip code
    Dim sResponseText As String, sReturn As String

    sReturn = "none"

    Dim objHttp As Object, sQuery As String
    sQuery = "http://rpc.geocoder.us/service/csv?address=" & Replace(sAddress, " ", "+")
    Set objHttp = CreateObject("Msxml2.ServerXMLHTTP")
    objHttp.Open "GET", sQuery, False
    objHttp.send
    sResponseText = objHttp.ResponseText
    gsLastLatLongResponseText = sResponseText
    Set objHttp = Nothing


    If Len(sResponseText) > 0 Then
        If InStr(sResponseText, "Bad Request") > 0 Then
            'Do Nothing
        ElseIf InStr(sResponseText, "couldn't find this address") > 0 Then
            'Do Nothing
        Else
            If InStr(sResponseText, vbCrLf) > 0 Then
                'We got more than one result
            End If
            If InStr(sResponseText, ",") > 0 Then
                Dim aryInfo() As String
                aryInfo = Split(sResponseText, ",")
                sReturn = aryInfo(0) & "," & aryInfo(1)
            End If
        End If
    End If


    fgGetLatAndLongUsingAddress = sReturn

End Function
vba geocode google-geocoder
2个回答
4
投票

这应该可以完成工作。您需要通过工具> Excel中的引用添加对MSXML6库(Microsoft XML,v6.0)的引用。

Option Explicit

Function getGoogleMapsGeocode(sAddr As String) As String

Dim xhrRequest As XMLHTTP60
Dim sQuery As String
Dim domResponse As DOMDocument60
Dim ixnStatus As IXMLDOMNode
Dim ixnLat As IXMLDOMNode
Dim ixnLng As IXMLDOMNode


' Use the empty string to indicate failure
getGoogleMapsGeocode = ""

Set xhrRequest = New XMLHTTP60
sQuery = "http://maps.googleapis.com/maps/api/geocode/xml?sensor=false&address="
sQuery = sQuery & Replace(sAddr, " ", "+")
xhrRequest.Open "GET", sQuery, False
xhrRequest.send

Set domResponse = New DOMDocument60
domResponse.loadXML xhrRequest.responseText
Set ixnStatus = domResponse.selectSingleNode("//status")

If (ixnStatus.Text <> "OK") Then
    Exit Function
End If

Set ixnLat = domResponse.selectSingleNode("/GeocodeResponse/result/geometry/location/lat")
Set ixnLng = domResponse.selectSingleNode("/GeocodeResponse/result/geometry/location/lng")

getGoogleMapsGeocode = ixnLat.Text & ", " & ixnLng.Text

End Function

您的示例的唯一实际区别是:

  • 更改查询的URL和参数以使用Google API
  • 将响应作为XML文档进行处理,并使用XPath提取所需的结果
  • 很显然,我的代码中没有任何错误处理,但是它应该使您了解使用API​​的需求。您绝对想亲自咨询API documentation来了解速率限制等


0
投票

感谢该代码!效果很好。感谢您注意速率限制。这就是谷歌必须说的:

© www.soinside.com 2019 - 2024. All rights reserved.