Missing Google JSON details
-
05-06-2021 - |
Question
Referencing this https://developers.google.com/maps/documentation/places/#PlaceDetails
I was expecting the JSON result to always hold all of the address_components
details. However, one of my searches ended up missing street_number, postal_code and one of the others. Looking in intellisense revealed one of the address_components
returned held an administrative_area_level_2.
This has thrown me into a loop because I was always expecting to have those original values returned even if they were maybe empty. I was also hardcoding the expected return like so:
array.result.address_components(0).long_name
Since I can't expect the components to return all the results, I need a new way to appropriately access them and figure out what to do when I'm missing some.
Solution
Here's the case statement I used to handle this problem. It worked, but not sure if it's the most elegant solution.
Dim street As String = ""
Dim city As String = ""
Dim state As String = ""
Dim country As String = ""
Dim zip As String = ""
Dim phone As String = ""
Dim website As String = ""
' No guareentee to the order of even if the data will be there so we check each type. '
For j = 0 To array.result.address_components.Length - 1
Select Case array.result.address_components(j).types(0)
Case "street_number"
street += array.result.address_components(j).long_name()
Case "route"
street += " " & array.result.address_components(j).long_name()
Case "locality"
city = array.result.address_components(j).long_name()
Case "administrative_area_level_1"
state = array.result.address_components(j).long_name()
Case "country"
country = array.result.address_components(j).long_name()
Case "postal_code"
zip = array.result.address_components(j).long_name()
End Select
Next
I basically cycle through the address_components and check their types value. If the value is one I'm looking for I assign it. I later call Trim() on street to remove that white space I add if there's no street number.