Android Question Parsing JSON Data (Google Maps Geocoding results)

Mike Webster

Member
Licensed User
I am banging my head into my desk trying to figure out how to parse the results from Google Maps to a geocoding request. I need to ultimately grab the location latitude and longitude from this but I am not having much luck. Below is a sample of the info returned by Google. If anyone could provide some guidance, I would appreciate it.

 

TILogistic

Expert
Licensed User
Longtime User
?
B4X:
    Dim parser As JSONParser
    parser.Initialize(Text)
    Dim mRoot As Map = parser.NextObject

    Dim status As String = mRoot.Get("status")
    Log(status)
  
    For Each colresults As Map In mRoot.Get("results").As(List)

        'Option 1
        Dim geometry As Map = colresults.Get("geometry")
        Dim location As Map = geometry.Get("location")
        Dim lat As Double = location.Get("lat")
        Dim lng As Double = location.Get("lng")
        Log($"${lat} / ${lng}"$)
      
        'Option 2
        Dim lat As Double = colresults.Get("geometry").As(Map).Get("location").As(Map).Get("lat")
        Dim lng As Double = colresults.Get("geometry").As(Map).Get("location").As(Map).Get("lng")
        Log($"${lat} / ${lng}"$)
    Next

 
Upvote 1

TILogistic

Expert
Licensed User
Longtime User
less code:
B4X:
    Dim mRoot As Map = Text.As(JSON).ToMap 'ignore
    Dim status As String = mRoot.Get("status")
    Log(status)
  
    For Each colresults As Map In mRoot.Get("results").As(List)
        Dim lat As Double = colresults.Get("geometry").As(Map).Get("location").As(Map).Get("lat")
        Dim lng As Double = colresults.Get("geometry").As(Map).Get("location").As(Map).Get("lng")
        Log($"${lat} / ${lng}"$)
    Next
 
Last edited:
Upvote 1

emexes

Expert
Licensed User
@oparra's solution is heaps better, but here's another approach { just in case | out of interest }:

regex for latitude = /"location".*?"lat"\s*:\s*(\-?\d*.?\d*)/gs

and similarly for longitude = /"location".*?"lng"\s*:\s*(\-?\d*.?\d*)/gs

 
Upvote 0

TILogistic

Expert
Licensed User
Longtime User
direct reading
B4X:
    Dim mRoot As Map = Text.As(JSON).ToMap 'ignore
    Dim lat As Double = mRoot.Get("results").As(List).Get(0).As(Map).Get("geometry").As(Map).Get("location").As(Map).Get("lat")
    Dim lng As Double = mRoot.Get("results").As(List).Get(0).As(Map).Get("geometry").As(Map).Get("location").As(Map).Get("lng")

    Log($"${lat},${lng}"$)
 
Upvote 1

emexes

Expert
Licensed User

That looks a bit verbose by your standards ? can you move common parts of the bottom two lines up into the top line?
 
Last edited:
Upvote 0
Cookies are required to use this site. You must accept them to continue using the site. Learn more…