Monday, December 22, 2014

Place Auto complete Using Google places API

Overview 


The Google Places Autocomplete API is a web service that returns Place information based on text search terms and, optionally, geographic bounds. The API can be used to provide autocomplete functionality for text-based geographic searches, by returning Places such as businesses, addresses, and points of interest as a user types.

private static final String LOG_TAG = ExampleApp";
private static final String PLACES_API_BASE = "https://maps.googleapis.com/maps/api/place";
private static final String TYPE_AUTOCOMPLETE = "/autocomplete";
private static final String OUT_JSON = "/json";
private static final String API_KEY = "YOUR_API_KEY";
private ArrayList autocomplete(String input) {
ArrayList resultList = null;
HttpURLConnection conn = null;
StringBuilder jsonResults = new StringBuilder();
try {
StringBuilder sb = new StringBuilder(PLACES_API_BASE +
TYPE_AUTOCOMPLETE + OUT_JSON);
sb.append("?key=" + API_KEY);
sb.append("&components=country:uk");
sb.append("&input=" + URLEncoder.encode(input, "utf8"));
URL url = new URL(sb.toString());
conn = (HttpURLConnection) url.openConnection();
InputStreamReader in = new InputStreamReader(conn.getInputStream());
// Load the results into a StringBuilder
int read;
char[] buff = new char[1024];
while ((read = in.read(buff)) != -1) {
jsonResults.append(buff, 0, read);
}
} catch (MalformedURLException e) {
Log.e(LOG_TAG, "Error processing Places API URL", e);
return resultList;
} catch (IOException e) {
Log.e(LOG_TAG, "Error connecting to Places API", e);
return resultList;
} finally {
if (conn != null) {
conn.disconnect();
}
}
return resultList;
}

 We will need a custom ListAdapter (ArrayAdapter implements the ListAdapter interface) to provide Place Autocomplete results to the AutoCompleteTextView.

private class PlacesAutoCompleteAdapter extends ArrayAdapter
implements Filterable {
private ArrayList resultList;
public PlacesAutoCompleteAdapter(Context context, int textViewResourceId)
{
super(context, textViewResourceId);
}

@Override

public int getCount() {

return resultList.size();

}

@Override

public String getItem(int index) {
return resultList.get(index);

}
@Override
public Filter getFilter() {
Filter filter = new Filter() {
@Override

protected FilterResults performFiltering(CharSequence constraint)
{
FilterResults filterResults = new FilterResults();

if (constraint != null) {
// Retrieve the autocomplete results.
resultList = autocomplete(constraint.toString());
// Assign the data to the FilterResults
filterResults.values = resultList;
filterResults.count = resultList.size();
}
return filterResults;
}

@Override
protected void publishResults(CharSequence constraint,
FilterResults results) {
if (results != null && results.count > 0) {
notifyDataSetChanged();
}
else {
notifyDataSetInvalidated();
}
}};
return filter;
}
}

Detect when a suggestion has been selected by the user, implement the OnItemClickListener interface and assign it to the AutoCompleteTextView.

public class PlacesAutocompleteActivity extends Activity implements

OnItemClickListener {

@Override

public void onCreate(Bundle savedInstanceState) {

AutoCompleteTextView autoCompView = (AutoCompleteTextView)

findViewById(R.id.autocomplete);

autoCompView.setAdapter(new PlacesAutoCompleteAdapter(this,
R.layout.list_item));

autoCompView.setOnItemClickListener(this);

public void onItemClick(AdapterView adapterView, View view, int
position, long id) {

String str = (String) adapterView.getItemAtPosition(position);

Toast.makeText(this, str, Toast.LENGTH_SHORT).show();

}

}
To instantiate an ArrayAdapter, We must include a reference to a layout file that contains a
TextView, Which corresponds to the Android layout file res/layout/list_item.xml
<!-- res/layout/list_item.xml -->
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content" />

API keys

The Place Autocomplete service is part of the Google Places API, and uses an API key to identify your application. API keys are managed through the Google APIs Console.

No comments:

Post a Comment