Android Tutorial Google Place

BarryW

Active Member
Licensed User
This is a simple tutorial on how to search a place using Google Place API and with you keyword.
Hope this can help for those who are confused... Like ME :):):)

First you need an API Key(Browser Key) that is describe in Erel's Google Map v2
http://www.b4x.com/android/forum/threads/google-maps-android-v2-tutorial.24415/

Note: I used a browser key because it can be test in our browser on computer also it can be used to android dev.
Ex: https://maps.googleapis.com/maps/api/place/textsearch/xmlquery=restaurants in Sydney&key=AddYourOwnKeyHere

Other request type can be found here:
https://developers.google.com/places/webservice/search

Then Parse the result using JSON Tree
http://www.b4x.com/android/forum/threads/jsontree-tool-to-help-with-json-parsing-b4a-b4j.35963/

Addition Libraries:
HTTP: http://www.b4x.com/android/help/http.html
JSON: http://www.b4x.com/android/forum/threads/android-json-tutorial.6923/
Reflection: http://www.b4x.com/android/forum/threads/reflection-library.6767/
StringUtils: http://www.b4x.com/android/help/stringutils.html

This is my code:
B4X:
Sub Process_Globals
    Dim ApiKey As String = "AIzaxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" 'Add your browser key here.
End Sub

Sub Globals
    Dim Button1 As Button, EditText1 As EditText, CustomListView1 As CustomListView
    Dim PlaceList As List 'Request result list.
End Sub

Sub Activity_Create(FirstTime As Boolean)
    Activity.LoadLayout("1")
    Button1.Background = LoadDrawable("ic_menu_search")
    CustomListView1.DefaultTextColor = Colors.Black
End Sub

Sub Activity_Resume
End Sub

Sub Activity_Pause (UserClosed As Boolean)
End Sub

Sub Button1_Click
    Dim KeyWord As String = EditText1.Text.Trim
    If KeyWord = "" Then Return 'Exit when keyword is blank.
    KeyWord = KeyWord.Replace(" ", "+") 'Required to replace all space by + to use in request query.
    Text_Search_Request(KeyWord)
End Sub

Sub Text_Search_Request(KeyWord As String)
    ProgressDialogShow("Searching...")
    Dim job As HttpJob
    job.Initialize("SearchPlace", Me)
    job.Download("https://maps.googleapis.com/maps/api/place/textsearch/json?query=" & KeyWord & "&key=" & ApiKey)
End Sub

Sub JobDone (Job As HttpJob)
    ProgressDialogHide
    Log("JobName = " & Job.JobName & ", Success = " & Job.Success)
    If Job.Success = True Then
        Select Job.JobName
            Case "SearchPlace"
                JsonTree(Job.getString)
        End Select
    Else
        Log("Error: " & Job.ErrorMessage)
        ToastMessageShow("Error: " & Job.ErrorMessage, True)
    End If
    Job.Release
End Sub

Sub JsonTree(JobString As String)
    PlaceList.Initialize
    Dim parser As JSONParser
    parser.Initialize(JobString)
    Dim root As Map = parser.NextObject
    Dim results As List = root.Get("results")
    For Each colresults As Map In results
        Dim TempMap As Map : TempMap.Initialize
      
        Dim name As String = colresults.Get("name")
        TempMap.Put("Name", name)
      
        Dim formatted_address As String = colresults.Get("formatted_address")
        TempMap.Put("Address", formatted_address)
      
        Dim types As List = colresults.Get("types")
        Dim TempType As String = ""
        For Each coltypes As String In types
            TempType = TempType & coltypes & " "
        Next
        TempMap.Put("Type", TempType)
      
        Dim geometry As Map = colresults.Get("geometry")
        Dim Location As Map = geometry.Get("location")
        Dim lng As Double = Location.Get("lng")
        Dim lat As Double = Location.Get("lat")
        TempMap.Put("Lat", lat)
        TempMap.Put("Lng", lng)
      
        PlaceList.Add(TempMap)
    Next
    Display_Result 'Display results to customlistview.
End Sub

Sub Display_Result
    CustomListView1.Clear
    For x = 0 To PlaceList.Size - 1
        Dim TempMap As Map = PlaceList.Get(x)
        Dim SB As StringBuilder
        SB.Initialize
        SB.Append("Name: ").Append(TempMap.Get("Name"))
        SB.Append(CRLF)
        SB.Append("Address: ").Append(TempMap.Get("Address"))
        SB.Append(CRLF)
        SB.Append("Type: ").Append(TempMap.Get("Type"))
        SB.Append(CRLF)
        SB.Append("Latitute: ").Append(TempMap.Get("Lat"))
        SB.Append(CRLF)
        SB.Append("Longhitute: ").Append(TempMap.Get("Lng"))
        CustomListView1.AddTextItem(SB.ToString, x)
    Next
End Sub

Sub LoadDrawable(Name As String) As Object
    'Gets a drawable from the Android system resources
    Dim R As Reflector
    R.Target = R.GetContext
    R.Target = R.RunMethod("getResources")
    R.Target = R.RunMethod("getSystem")
    Dim ID_Drawable As Int
    ID_Drawable = R.RunMethod4("getIdentifier", Array As Object(Name, "drawable", "android"), _
                                                Array As String("java.lang.String", "java.lang.String", "java.lang.String"))
    R.Target = R.GetContext
    R.Target = R.RunMethod("getResources")
    Return R.RunMethod2("getDrawable", ID_Drawable, "java.lang.int")
End Sub
Also thanks to warwound (CustomListView)
http://www.b4x.com/android/forum/threads/custom-listview-library.17708/
 

Attachments

lemonisdead

Well-Known Member
Licensed User
Hello,
Nice tutorial. Perhaps should you urlEncode the query using StringUtils for more security
 

BarryW

Active Member
Licensed User
My url is not visible when users use the compiled apk so no need to encode it. Anyway thank you for your good suggestion...
 

shashkiranr

Active Member
Licensed User
Hi BarryW,

Thank you for this tutorial. I have loaded my API key obtained in the the google maps tutorial. I am able to use that to locate places using lat and long but I am not able to retrieve the places using the above tutorial. When i checked the unfiltered logs i got the following error
B4X:
Couldn't connect to Google API client: ConnectionResult{statusCode=API_UNAVAILABLE, resolution=null}
Any idea how to resolve this?

Regards,
SK
 

shashkiranr

Active Member
Licensed User
Hi I Got it working. I had put the SHA1 along with my package name in the browser key Referrers. I kept it blank and it is working. SO my question is what do you give in the Referrers for the browser key. ? For andriod we give the SHA1 key along with package name but for this its working only if it empty !

Any suggestion?

Regards,
SK
 

BarryW

Active Member
Licensed User
Just leave it blank. Make sure you use browser key for google place not an android key.
 

Reids

Member
Licensed User
Hi BarryW,

Thank you for this tutorial. I have loaded my API key obtained in the the google maps tutorial. I am able to use that to locate places using lat and long but I am not able to retrieve the places using the above tutorial. When i checked the unfiltered logs i got the following error
B4X:
Couldn't connect to Google API client: ConnectionResult{statusCode=API_UNAVAILABLE, resolution=null}
Any idea how to resolve this?

Regards,
SK
enable this API not normal GOOGLE MAP API and then put the key inside the b4a api key section
 

Attachments

henry montoya

Member
Licensed User
Hi.

excellent contribution I've tried it and I liked it a lot, but I wonder if it is possible as autocomplete and not as search, I know this thread has been a while so thanks for all the possible collaboration.
 

Matias Ferrer

Member
Licensed User
Hey there,
I have a problem when compiling.

He throws me the following error:

Error:

B4A line: 53
Log ( Response.GetString ( \
javac 1.8.0_60
src \ com \ domain \ appname \ httputils2service.java : 163 : error : can not access ParseException
anywheresoftware.b4a.keywords.Common.Log ( _response.GetString ( " UTF8 "));
^
org.apache.http.ParseException file for class not found

If I delete the log line (line 53 )

I give this another mistake ..

Compiling Java code generated . Error
B4A line: 16
hc.Initialize ( \
javac 1.8.0_60
src \ com \ domain \ appname \ httputils2service.java : 223 : error : can not access ClientProtocolException
_hc.Initialize ( " HC" ) ;
^
org.apache.http.client.ClientProtocolException file for class not found

I suggest something ?

Thank you!
 

Mashiane

Expert
Licensed User
This is a simple tutorial on how to search a place using Google Place API and with you keyword.
Hope this can help for those who are confused... Like ME :):):)

First you need an API Key(Browser Key) that is describe in Erel's Google Map v2
http://www.b4x.com/android/forum/threads/google-maps-android-v2-tutorial.24415/

Note: I used a browser key because it can be test in our browser on computer also it can be used to android dev.
Ex: https://maps.googleapis.com/maps/api/place/textsearch/xmlquery=restaurants in Sydney&key=AddYourOwnKeyHere

Other request type can be found here:
https://developers.google.com/places/webservice/search

Then Parse the result using JSON Tree
http://www.b4x.com/android/forum/threads/jsontree-tool-to-help-with-json-parsing-b4a-b4j.35963/

Addition Libraries:
HTTP: http://www.b4x.com/android/help/http.html
JSON: http://www.b4x.com/android/forum/threads/android-json-tutorial.6923/
Reflection: http://www.b4x.com/android/forum/threads/reflection-library.6767/
StringUtils: http://www.b4x.com/android/help/stringutils.html

This is my code:
B4X:
Sub Process_Globals
    Dim ApiKey As String = "AIzaxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" 'Add your browser key here.
End Sub

Sub Globals
    Dim Button1 As Button, EditText1 As EditText, CustomListView1 As CustomListView
    Dim PlaceList As List 'Request result list.
End Sub

Sub Activity_Create(FirstTime As Boolean)
    Activity.LoadLayout("1")
    Button1.Background = LoadDrawable("ic_menu_search")
    CustomListView1.DefaultTextColor = Colors.Black
End Sub

Sub Activity_Resume
End Sub

Sub Activity_Pause (UserClosed As Boolean)
End Sub

Sub Button1_Click
    Dim KeyWord As String = EditText1.Text.Trim
    If KeyWord = "" Then Return 'Exit when keyword is blank.
    KeyWord = KeyWord.Replace(" ", "+") 'Required to replace all space by + to use in request query.
    Text_Search_Request(KeyWord)
End Sub

Sub Text_Search_Request(KeyWord As String)
    ProgressDialogShow("Searching...")
    Dim job As HttpJob
    job.Initialize("SearchPlace", Me)
    job.Download("https://maps.googleapis.com/maps/api/place/textsearch/json?query=" & KeyWord & "&key=" & ApiKey)
End Sub

Sub JobDone (Job As HttpJob)
    ProgressDialogHide
    Log("JobName = " & Job.JobName & ", Success = " & Job.Success)
    If Job.Success = True Then
        Select Job.JobName
            Case "SearchPlace"
                JsonTree(Job.getString)
        End Select
    Else
        Log("Error: " & Job.ErrorMessage)
        ToastMessageShow("Error: " & Job.ErrorMessage, True)
    End If
    Job.Release
End Sub

Sub JsonTree(JobString As String)
    PlaceList.Initialize
    Dim parser As JSONParser
    parser.Initialize(JobString)
    Dim root As Map = parser.NextObject
    Dim results As List = root.Get("results")
    For Each colresults As Map In results
        Dim TempMap As Map : TempMap.Initialize
     
        Dim name As String = colresults.Get("name")
        TempMap.Put("Name", name)
     
        Dim formatted_address As String = colresults.Get("formatted_address")
        TempMap.Put("Address", formatted_address)
     
        Dim types As List = colresults.Get("types")
        Dim TempType As String = ""
        For Each coltypes As String In types
            TempType = TempType & coltypes & " "
        Next
        TempMap.Put("Type", TempType)
     
        Dim geometry As Map = colresults.Get("geometry")
        Dim Location As Map = geometry.Get("location")
        Dim lng As Double = Location.Get("lng")
        Dim lat As Double = Location.Get("lat")
        TempMap.Put("Lat", lat)
        TempMap.Put("Lng", lng)
     
        PlaceList.Add(TempMap)
    Next
    Display_Result 'Display results to customlistview.
End Sub

Sub Display_Result
    CustomListView1.Clear
    For x = 0 To PlaceList.Size - 1
        Dim TempMap As Map = PlaceList.Get(x)
        Dim SB As StringBuilder
        SB.Initialize
        SB.Append("Name: ").Append(TempMap.Get("Name"))
        SB.Append(CRLF)
        SB.Append("Address: ").Append(TempMap.Get("Address"))
        SB.Append(CRLF)
        SB.Append("Type: ").Append(TempMap.Get("Type"))
        SB.Append(CRLF)
        SB.Append("Latitute: ").Append(TempMap.Get("Lat"))
        SB.Append(CRLF)
        SB.Append("Longhitute: ").Append(TempMap.Get("Lng"))
        CustomListView1.AddTextItem(SB.ToString, x)
    Next
End Sub

Sub LoadDrawable(Name As String) As Object
    'Gets a drawable from the Android system resources
    Dim R As Reflector
    R.Target = R.GetContext
    R.Target = R.RunMethod("getResources")
    R.Target = R.RunMethod("getSystem")
    Dim ID_Drawable As Int
    ID_Drawable = R.RunMethod4("getIdentifier", Array As Object(Name, "drawable", "android"), _
                                                Array As String("java.lang.String", "java.lang.String", "java.lang.String"))
    R.Target = R.GetContext
    R.Target = R.RunMethod("getResources")
    Return R.RunMethod2("getDrawable", ID_Drawable, "java.lang.int")
End Sub
Also thanks to warwound (CustomListView)
http://www.b4x.com/android/forum/threads/custom-listview-library.17708/
Perfect, thank you so so so much...
 

Filippo

Expert
Licensed User
Thanks for this tutorial. :)
 
Top