Steve-vfp9user
Programmer
Hello all,
I am trying to find a way of a user entering a postcode for an address look up which I can later use when we create an order. I have tried the below but without success so I am asking for advice on what is wrong with the below or do the expert users know some other way to do this? When I run the code, there are no errors but I do not get a result which should be 10 Downing Street, London SW1A 2AA, UK.
I am only wanting addresses in the UK, here's what I have so far:
Much appreciated.
I am trying to find a way of a user entering a postcode for an address look up which I can later use when we create an order. I have tried the below but without success so I am asking for advice on what is wrong with the below or do the expert users know some other way to do this? When I run the code, there are no errors but I do not get a result which should be 10 Downing Street, London SW1A 2AA, UK.
I am only wanting addresses in the UK, here's what I have so far:
Code:
PROCEDURE GetAddressFromPostcode
LOCAL oHttp, cUrl, cResponse, cPostcode, cApiKey, cFormattedAddress
* Set your API key
cApiKey = "123456" && This is a dummy API key (I do have Google API one)
cPostcode="SW1A 2AA" && This is 10 Downing Street as an exmple!
* Validate input
IF EMPTY(cPostcode)
Wait "No postcode entered" WINDOW NOWAIT
RETURN
ENDIF
* Build the API request URL
cUrl = "https://maps.googleapis.com/maps/api/place/textsearch/json?query=" + ;
cPostcode + "&key=" + cApiKey
* Create HTTP request object
oHttp = CREATEOBJECT("WinHttp.WinHttpRequest.5.1")
oHttp.Open("GET", cUrl, .F.)
oHttp.Send()
* Get response from Google API
cResponse = oHttp.ResponseText
* Check if response is valid
IF EMPTY(cResponse) OR "error" $ cResponse
=MESSAGEBOX("Invalid postcode or API error.", 48, "Error")
RETURN
ENDIF
* Extract the formatted address
cFormattedAddress = ExtractFormattedAddress(cResponse)
* Show the result
IF EMPTY(cFormattedAddress)
=MESSAGEBOX("No address found for this postcode.", 48, "Not Found")
ELSE
MESSAGEBOX("Address Found: " + cFormattedAddress, 64, "Success")
ENDIF
ENDPROC
FUNCTION ExtractFormattedAddress(cJsonString)
LOCAL cAddress, nStart, nEnd
* Find the position of "formatted_address"
nStart = AT('"formatted_address" : "', cJsonString) + 22
nEnd = AT('"', cJsonString, nStart + 1)
* Extract the address
IF nStart > 22 AND nEnd > nStart
cAddress = SUBSTR(cJsonString, nStart, nEnd - nStart)
ELSE
cAddress = ""
ENDIF
RETURN cAddress
ENDFUNC
Much appreciated.