Google Places Autocomplete

By in , , ,
No comments

Main Objective of this blog post is to explain how to integrate autocomplete places in an Android Studio .

The autocomplete service in the Google Places API for Android returns place predictions in response to user search queries.

The autocomplete widget is a search dialog with built-in autocomplete functionality. As a user enters search terms, the widget presents a list of predicted places to choose from. When the user makes a selection, a Place instance is returned, which your app can then use to get details about the selected place.

A new API was released for Android, by the name of Google Places API. This API offers easy to use methods, through which Google Places data can be accessed on Android.

1.In order to use Google Places API first, we need a key and enabled Google Places API.Create a key here.

 

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.

“Create”  Key for accessing the right results from our Google Places API call.

 

2. We need to add Internet Permission in applications AndroidManifest file.

  1. <uses-permission android:name=“android.permission.INTERNET”/>

 

3. To implement Google places we need:-

We are going to make a simple layout xml for the AutocompleteActivity.class, that consists of a LinearLayoutwith vertical orientation, that includes one AutoCompleteTextView that implement the onClick listener in order to catch the event when clicked.

Open res/layout/autocompelete.xml, go to the respective xml tab and paste the following:

autocompelete.xml

<LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"
 xmlns:tools="http://schemas.android.com/tools"
 android:id="@+id/activity_sign_up"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
>
 <AutoCompleteTextView
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:padding="10dp"
 android:singleLine="true"
 android:maxLength="50"
 android:inputType="text"
 android:id="@+id/edittext_signup_city"
 android:textSize="16dp"

android:digits="@string/alphabet"
 android:textColorHint="@color/robotolightblack"
 android:background="@drawable/line"
 android:hint="@string/Enter_city"/>
</linearlayout>

4. Now i will code for AutocompleteActivity.java setting adapter to autocomplete text view and handling click for it.

AutocompleteActivity.java

public class SignUpActivity extends Activity {

AutoCompleteTextView edittext_signup_city;
AsyncTask<Void, Void, Void> mRegisterTask;
private static final String TAG_RESULT = "predictions";
JSONObject json;
ArrayList<String> names;
ArrayAdapter<String> adapter;
String browserKey = "Your google api key ";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sign_up);
names = new ArrayList<String>();

edittext_signup_city.addTextChangedListener(new TextWatcher() {

public void afterTextChanged(Editable s) {

}

public void beforeTextChanged(CharSequence s, int start, int count,
int after) {

}

public void onTextChanged(CharSequence s, int start, int before,
int count) {

if (s.toString().length() <= 3) {
names = new ArrayList<String>();
System.out.println("2"+s.toString());
updateList(s.toString());
}

}
});
}

//------------------------AutoComplete code--------------

public void updateList(String place) {
String input = "";

try {
input = "input=" + URLEncoder.encode(place, "utf-8");
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
}

String output = "json";
String parameter = input + "&components=country:in&components=locality:redmond&types=(cities)&sensor=true&key="
+ browserKey;

// https://maps.googleapis.com/maps/api/place/autocomplete/json?key=&types=(cities)&input=
url = "https://maps.googleapis.com/maps/api/place/autocomplete/"
+ output + "?" + parameter;

JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.GET, url,
null, new Response.Listener<JSONObject>() {

@Override
public void onResponse(JSONObject response) {
System.out.println("response"+response);
try {

JSONArray ja = response.getJSONArray(TAG_RESULT);

for (int i = 0; i < ja.length(); i++) {
JSONObject c = ja.getJSONObject(i);
String description = c.getString("description");
System.out.println("description"+description);
names.add(description);
}

adapter = new ArrayAdapter<String>(
getApplicationContext(),
android.R.layout.simple_list_item_1, names) {
@Override
public View getView(int position,
View convertView, ViewGroup parent) {
View view = super.getView(position,
convertView, parent);
TextView text = (TextView) view
.findViewById(android.R.id.text1);
text.setTextColor(Color.BLACK);



return view;
}
};
edittext_signup_city.setAdapter(adapter);
adapter.notifyDataSetChanged();
} catch (Exception e) {
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
}
});
AppController.getInstance().addToRequestQueue(jsonObjReq, "jreq");
}

}

Get place predictions programmatically

You can create a custom search UI as an alternative to the UI provided by the autocomplete widget. To do this, your app must get place predictions programmatically. Your app can get a list of predicted place names and/or addresses from the autocomplete service by calling GeoDataApi.getAutocompletePredictions(), passing the following parameters:

  • Required: A query string containing the text typed by the user.
  • Required: A LatLngBounds object, biasing the results to a specific area specified by latitude and longitude bounds.
  • Optional: An AutocompleteFilter containing a set of place types, which you can use to restrict the results to one or more types of place. The following place types are supported:
    • TYPE_FILTER_NONE – An empty filter; all results are returned.
    • TYPE_FILTER_GEOCODE – Returns only geocoding results, rather than businesses. Use this request to disambiguate results where the specified location may be indeterminate.
    • TYPE_FILTER_ADDRESS – Returns only autocomplete results with a precise address. Use this type when you know the user is looking for a fully specified address.
    • TYPE_FILTER_ESTABLISHMENT – Returns only places that are businesses.
    • TYPE_FILTER_REGIONS – Returns only places that match one of the following types:
      • locality
      • sublocality
      • postal_code
      • country
      • administrative_area_level_1
      • administrative_area_level_2
    • TYPE_FILTER_CITIES – Returns only results matching locality oradministrative_area_level_3.

API Keys

There’s some information regarding where you should store your API Key at the end of this article that you should go through once.

 


Source: https://developers.google.com/places/android-api/autocomplete

Thank You.

Please follow and like us:
0
3+

Users who have LIKED this post:

  • avatar

Leave a Reply

Your email address will not be published. Required fields are marked *