Getting the Longitude and Latitude for an Address
Just finished answering a question out on UniversalThread regarding how to get the Longitude and Latitude from an address. Following is the Visual FoxPro code I came up with for doing it. I’m posting it here simply so I can find it later (maybe a few readers will find it interesting or useful too). In any event, here’s the code…


LOCAL lcAddress, lcLongitude, lcLatitude
m.lcAddress = “7651 209th Street North,Forest Lake,MN”
GetLongLatFromAddress(m.lcAddress, @m.lcLongitude, @m.lcLatitude)
MESSAGEBOX(“Longitude: “ + m.lcLongitude + CHR(13) + “Latitude: “ + m.lcLatitude, 64, “Geo Information”)

************************
FUNCTION GetLongLatFromAddress(tcAddress, tcLongitude, tcLatitude)
************************
LOCAL lcAddress, lcURL, loXMLHTTP as MSXML2.XMLHTTP, lcReturn
m.loXMLHTTP = CreateObject(“MSXML2.XMLHTTP”)
m.lcAddress = UrlEncode(m.tcAddress, .F.)
m.lcAddress = HandleUnsafeChars(m.lcAddress)
m.lcURL = “http://rpc.geocoder.us/service/rest?address=” + m.lcAddress
m.loXMLHTTP.open(“GET”, m.lcURL, .F.) && third parameter needed to avoid need to check readyState
m.loXMLHTTP.send()
m.lcReturn = m.loXMLHTTP.responseText
m.tcLongitude = STREXTRACT(m.lcReturn,“<geo:long>”, “</geo:long>”,1,1)
m.tcLatitude = STREXTRACT(m.lcReturn,“<geo:lat>”, “</geo:lat>”,1,1)
RETURN m.lcReturn
ENDFUNC

************************
FUNCTION UrlEncode(tcString, tlNoPlus)
    ************************
    LOCAL lcReturn, lcChar, lnCounter
    m.lcReturn=“”
    FOR m.lnCounter = 1 TO LEN(m.tcString)
        m.lcChar = SUBSTR(m.tcString, m.lnCounter, 1)
        IF ATC(m.lcChar,“ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789”) > 0
            m.lcReturn = m.lcReturn + m.lcChar
            LOOP
        ENDIF
        IF ASC(m.lcChar) = 32 AND !m.tlNoPlus
            m.lcReturn = m.lcReturn + “+”
            LOOP
        ENDIF
        m.lcReturn = m.lcReturn + “%” + RIGHT(TRANSFORM(ASC(m.lcChar),“@0”),2)
    ENDFOR
    RETURN m.lcReturn
ENDFUNC

************************
FUNCTION HandleUnsafeChars(tcString)
    ************************
    LOCAL lcReturn, lcBuffer, lnBufferSize
    #DEFINE ICU_BROWSER_MODE 0x2000000
    DECLARE INTEGER InternetCanonicalizeUrl IN wininet;
        STRING sURL, STRING @sBUFFER, INTEGER @nLength, INTEGER nFlags
    m.lnBufferSize = 250
    m.lcBuffer = REPLICATE(CHR(0), m.lnBufferSize)
    IF InternetCanonicalizeUrl (m.tcString, @m.lcBuffer, @m.lnBufferSize, ICU_BROWSER_MODE) != 0
        m.lcReturn = LEFT(m.lcBuffer, m.lnBufferSize)
    ELSE
        m.lcReturn = “”
    ENDIF
    RETURN m.lcReturn
ENDFUNC