Android Google Places API Example
In the example, we are going to see how can we use one of the most famous, public, social APIs, The Google Places API.
The Google Places API allows you to query for place information on a variety of categories, such as: establishments, prominent points of interest, geographic locations, and more. You can search for places either by proximity or a text string.
A Place Search returns a list of places along with summary information about each place; additional information is available via a Place Details query. You can see the full Google Places API documentation here: https://developers.google.com/places/documentation/.
In our example we are going to discuss how to make a places search or explore request with the Google Places API and how to parse these results. Our call is not going to be a userless one, we will have to create a special Google API Key.
But, lets’ see this procedure step by step.
1. Create the Google API key
To begin with, in order to use this API, we will have to enter the Google API console portal.
After we enter the console,we are going to see the full list, of all the APIs that Google serves. The API that we are going to use, is the Google Places API. We click on the right service, and we turn it on. We have to accept the terms of Google Maps/Earth API, by ticking the checkbox and by clicking the “Accept” button.
Now we can see the enabled APIs that this console user has.
In the “Overview” tab, we can have a look on the usage statistics for each one of our APIs that are enabled. We can also have a look on our quota limits for each one of our APIs.
You can see here what exactly is the quota limit: https://developers.google.com/gmail/api/v1/reference/quota
However, if we make the Google Places API search call from a browser, we will get as response the following:
We are going to create a Public API access credential, in order to take the right response from the Google Places API search call. We only have to go to APIs&auth > Credentials tab.
We click the “Create new Key” button, and select the “Server Key” in order to make a Key that will both work from our Android Application and from our browser. We are going to do this, exclusively for our example scope.
If you want to publish an application to the Google Play Store, that uses any of these Google API calls, you should create an Android key, by using the SHA-1 key of your original keystore (not the debug one) of the application to be exported.
Now, we are going to create a server key and configure the allowed IPs, by writing them on the “Accept Requests from these server IP address” textfield.
After clicking on the “Create” button, we have our Key for accessing the right results from our Google Places API call.
2. Create a the Android Application Project
Let’s start coding now! For our example will use the following tools in a Windows 64-bit or an OS X platform:
- JDK 1.7
- Eclipse 4.2 Juno
- Android SDK 4.4.2
Let’s take a closer look:
You may skip project creation and jump directly to the beginning of the example below.
Open Eclipse IDE and go to File → New → Project → Android Application Project.
Specify the name of the application, the project and the package and then click Next.
In the next window, the “Create Activity” option should be checked. The new created activity will be the main activity of your project. Then press Next button.
In “Configure Launcher Icon” window you should choose the icon you want to have in your app. We will use the default icon of android, so click Next.
Select the “Blank Activity” option and press Next.
You have to specify a name for the new Activity and a name for the layout description of your app. The .xml file for the layout will automatically be created in the res/layout folder. It will also be created a fragment layout xml, that we are not going to use in this project and you can remove it if you want. Then press Finish.
Here you can see, how will the structure of the project become when finished:
3. Creating the layout of the main Google Places Example
We are going to make a very simple layout xml for the GooglePlacesExample.class
, that only consists of a LinearLayout
that contains the one ListView
.
Open res/layout/activity_main.xml
, go to the respective xml tab and paste the following:
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:background="#ffffff" android:orientation="vertical" > <ListView android:id="@android:id/list" android:layout_width="match_parent" android:layout_height="wrap_content" > </ListView> </LinearLayout>
4. Creating the source code of the main GooglePlacesExample
Before we make the call to the Google Places API and we parse the results, we should have a look to the json response that we are going to take.
We have the call: https://maps.googleapis.com/maps/api/place/search/json?location=40.7463956,-73.9852992&radius=100&sensor=true&key={key}
For this call, we used the parameters:
- GOOGLE_KEY: The specific credentials we generated above
- 40.7463956: The latitude of the point that we are going to search from
- -73.9852992: The longitude of the point that we are going to search from
We will use the center of New York, USA, for our venues search. This is the response we get:
Google Places API
{ "html_attributions" : [], "next_page_token" : "CvQB7AAAAPzh-eaLooQJ1gxg88_EmHbqLfFt45aahApotdjuy70UqAyx07tuoRCpVM2gbDfpf8YfIbkZ96bzIo8T-6x3a-K8GXlgEX9_gULyzmfsGAhiK7yvc9N_P7nGqyS3pOSCxPAHYLZ7Id5zabLwXOllviOPItH5788c1A-7K-a8IfLp9aGn94ikX-ei40wKlIEGr8SWfle5Unmk0L_qIZOD8Xn_yNa3a4JFPby2affcEi0Kg1eEkEkkngSL-T8wXkjLS82gl_1FlmfMSvRvok5GJ90gmy72yhB5j88wyZLlrZvnVqwuXD0bmEMD_9eEwLm4pBIQA1GcTSIXRswedriQX3gTPBoUEE-rgsd8cPKvpg9ugEKrIy-o31Q", "results" : [ { "geometry" : { "location" : { "lat" : 40.7477385, "lng" : -73.98689379999999 }, "viewport" : { "northeast" : { "lat" : 40.749029, "lng" : -73.98506640000001 }, "southwest" : { "lat" : 40.7465661, "lng" : -73.9883493 } } }, "icon" : "http://maps.gstatic.com/mapfiles/place_api/icons/geocode-71.png", "id" : "e175a5f113997bf0b6515718a67ce6cabc821bf4", "name" : "Korea Town", "place_id" : "ChIJ_f1FDqlZwokRqCItRNuQIKs", "reference" : "CpQBiAAAAKjvKpniYmo7fcXUlXZi0rwKJIObZ2YdZfHW1oN2hYqWZBlJcfbbmbCe9s68497cdtEoOQalVthvJAS7A92EI1o4qXuxhonTaA7UOjcRS30xm4VNmvFFSDMjVx5B1nxWr0dx8mSsRY3ygbWw1d1-Tgxr_sO_LE8bsoRzezYlGM25BRq-6QCrzrzsWqu07-UIqhIQjFSlTMx4T9RqZAX1GCkevxoU4be-kyQ5hudhV8fnI2GpPWq-MFA", "scope" : "GOOGLE", "types" : [ "neighborhood", "political" ], "vicinity" : "Manhattan" }, ], status: "OK" }
5. Creating the source code of the main GooglePlacesExample
We are going to create the main Activity of our example application. Open src/com.javacodegeeks.androidgoogleplaces/GooglePlacesExample.java
file and paste the code below.
GooglePlacesExample.java
package com.javacodegeeks.androidgoogleplaces; import java.io.BufferedInputStream; import java.io.InputStream; import java.util.ArrayList; import java.util.List; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.util.ByteArrayBuffer; import org.json.JSONArray; import org.json.JSONObject; import android.app.ListActivity; import android.os.AsyncTask; import android.os.Bundle; import android.view.View; import android.widget.ArrayAdapter; public class GooglePlacesExample extends ListActivity { ArrayList venuesList; // the google key // ============== YOU SHOULD MAKE NEW KEYS ====================// final String GOOGLE_KEY = "AIzaSyDe73ubloXet5TLk91EWgynvKU"; // we will need to take the latitude and the logntitude from a certain point // this is the center of New York final String latitude = "40.7463956"; final String longtitude = "-73.9852992"; ArrayAdapter myAdapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // start the AsyncTask that makes the call for the venus search. new googleplaces().execute(); } private class googleplaces extends AsyncTask { String temp; @Override protected String doInBackground(View... urls) { // make Call to the url temp = makeCall("https://maps.googleapis.com/maps/api/place/search/json?location=" + latitude + "," + longtitude + "&radius=100&sensor=true&key=" + GOOGLE_KEY); //print the call in the console System.out.println("https://maps.googleapis.com/maps/api/place/search/json?location=" + latitude + "," + longtitude + "&radius=100&sensor=true&key=" + GOOGLE_KEY); return ""; } @Override protected void onPreExecute() { // we can start a progress bar here } @Override protected void onPostExecute(String result) { if (temp == null) { // we have an error to the call // we can also stop the progress bar } else { // all things went right // parse Google places search result venuesList = (ArrayList) parseGoogleParse(temp); List listTitle = new ArrayList(); for (int i = 0; i < venuesList.size(); i++) { // make a list of the venus that are loaded in the list. // show the name, the category and the city listTitle.add(i, venuesList.get(i).getName() + "\nOpen Now: " + venuesList.get(i).getOpenNow() + "\n(" + venuesList.get(i).getCategory() + ")"); } // set the results to the list // and show them in the xml myAdapter = new ArrayAdapter(GooglePlacesExample.this, R.layout.row_layout, R.id.listText, listTitle); setListAdapter(myAdapter); } } } public static String makeCall(String url) { // string buffers the url StringBuffer buffer_string = new StringBuffer(url); String replyString = ""; // instanciate an HttpClient HttpClient httpclient = new DefaultHttpClient(); // instanciate an HttpGet HttpGet httpget = new HttpGet(buffer_string.toString()); try { // get the responce of the httpclient execution of the url HttpResponse response = httpclient.execute(httpget); InputStream is = response.getEntity().getContent(); // buffer input stream the result BufferedInputStream bis = new BufferedInputStream(is); ByteArrayBuffer baf = new ByteArrayBuffer(20); int current = 0; while ((current = bis.read()) != -1) { baf.append((byte) current); } // the result as a string is ready for parsing replyString = new String(baf.toByteArray()); } catch (Exception e) { e.printStackTrace(); } System.out.println(replyString); // trim the whitespaces return replyString.trim(); } private static ArrayList parseGoogleParse(final String response) { ArrayList temp = new ArrayList(); try { // make an jsonObject in order to parse the response JSONObject jsonObject = new JSONObject(response); // make an jsonObject in order to parse the response if (jsonObject.has("results")) { JSONArray jsonArray = jsonObject.getJSONArray("results"); for (int i = 0; i < jsonArray.length(); i++) { GooglePlace poi = new GooglePlace(); if (jsonArray.getJSONObject(i).has("name")) { poi.setName(jsonArray.getJSONObject(i).optString("name")); poi.setRating(jsonArray.getJSONObject(i).optString("rating", " ")); if (jsonArray.getJSONObject(i).has("opening_hours")) { if (jsonArray.getJSONObject(i).getJSONObject("opening_hours").has("open_now")) { if (jsonArray.getJSONObject(i).getJSONObject("opening_hours").getString("open_now").equals("true")) { poi.setOpenNow("YES"); } else { poi.setOpenNow("NO"); } } } else { poi.setOpenNow("Not Known"); } if (jsonArray.getJSONObject(i).has("types")) { JSONArray typesArray = jsonArray.getJSONObject(i).getJSONArray("types"); for (int j = 0; j < typesArray.length(); j++) { poi.setCategory(typesArray.getString(j) + ", " + poi.getCategory()); } } } temp.add(poi); } } } catch (Exception e) { e.printStackTrace(); return new ArrayList(); } return temp; } }
We also have a helper class for the Google Places response parsing. Open src/com.javacodegeeks.androidgoogleplaces/GooglePlace.java
file and paste the code below.
GooglePlace.java
package com.javacodegeeks.androidgoogleplaces; public class GooglePlace { private String name; private String category; private String rating; private String open; public GooglePlace() { this.name = ""; this.rating = ""; this.open = ""; this.setCategory(""); } public void setName(String name) { this.name = name; } public String getName() { return name; } public String getCategory() { return category; } public void setCategory(String category) { this.category = category; } public void setRating(String rating) { this.rating = rating; } public String getRating() { return rating; } public void setOpenNow(String open) { this.open = open; } public String getOpenNow() { return open; } }
6. Android Manifest
In order to call execute this call, we should have access to the Internet. This must be specified in the manifest, so that, our application will be granted the permission to use the Internet connection. The AndroidManifest.xml of our project is simple and contains the permissions:
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.javacodegeeks.androidgoogleplaces" android:versionCode="1" android:versionName="1.0" > <uses-permission android:name="android.permission.INTERNET" /> <uses-sdk android:minSdkVersion="8" android:targetSdkVersion="19" /> <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" > <activity android:name="com.javacodegeeks.androidgoogleplaces.GooglePlacesExample" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest>
7. Build, compile and run
When we build, compile and run our project, the main GooglePlacesExample should look like this:
Download the Eclipse Project
This was an example of Android Foursquare API Venues Search API.
You can download the full source code of this example here: AndroidGooglePlacesApiExample