Android Autocomplete Location Search
First visit
And Create A New Project And Generate a API key
After That Create A New Android studio Project
Then edit build.gradle file and google library dependency
After That Create A New Android studio Project
Then edit build.gradle file and google library dependency
compile 'com.google.android.gms:play-services-location:11.8.0' compile 'com.android.volley:volley:1.1.0'
like this in build.gradle.
After that sync now
Then open AndroidManifest.xml file and add meta for Data And Value for google api which we generate in first step.
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.sswebtricks.sanjeev.autocompletelocation">
<uses-permission android:name="android.permission.INTERNET"/>
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<meta-data android:name="com.google.android.geo.API_KEY" android:value="API KEY PUT HERE"/>
</application>
</manifest>
package com.sswebtricks.sanjeev.autocompletelocation;
import android.util.Log;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
/**
* Created by sanjeev on 4/2/18.
*/
public class LocationModel {
private static final String TAG = LocationModel.class.getSimpleName();
private static final String URL = "https://maps.googleapis.com/maps/api/place";
private static final String API_TYPE = "/autocomplete";
private static final String OUTPUT = "/json";
private static final String KEY = "YOUR_API_KEY";
public ArrayList autocomplete (String input) {
ArrayList resultList = null;
HttpURLConnection conn = null;
StringBuilder jsonResults = new StringBuilder();
try {
StringBuilder sb = new StringBuilder(URL + API_TYPE + OUTPUT);
sb.append("?key=" + KEY);
sb.append("&types=(cities)");
sb.append("&input=" + URLEncoder.encode(input, "utf8"));
URL url = new URL(sb.toString());
conn = (HttpURLConnection) url.openConnection();
InputStreamReader in = new InputStreamReader(conn.getInputStream());
int read;
char[] buff = new char[1024];
while ((read = in.read(buff)) != -1) {
jsonResults.append(buff, 0, read);
}
} catch (MalformedURLException e) {
Log.e(TAG, "Api Error", e);
return resultList;
} catch (IOException e) {
Log.e(TAG, "Connection Error", e);
return resultList;
} finally {
if (conn != null) {
conn.disconnect();
}
}
try {
JSONObject Object = new JSONObject(jsonResults.toString());
JSONArray PredictArray = Object.getJSONArray("predictions");
resultList = new ArrayList(PredictArray.length());
for (int i = 0; i < PredictArray.length(); i++) {
resultList.add(PredictArray.getJSONObject(i).getString("description"));
}
} catch (JSONException e) {
Log.e(TAG, "Cannot Parse Json", e);
}
return resultList;
}
}
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.sswebtricks.sanjeev.autocompletelocation.MainActivity">
<LinearLayout
android:padding="10dp"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<AutoCompleteTextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/autocomplete"
android:hint="Type in your Location" />
</LinearLayout>
<LinearLayout
android:padding="5dp"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:padding="5dp"
android:layout_weight="1"
android:id="@+id/lat"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<TextView
android:padding="5dp"
android:layout_weight="1"
android:id="@+id/lng"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
</LinearLayout>
</RelativeLayout>
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="#000"
android:padding="10dp"
android:text="Location"
android:id="@+id/autocompleteText" />
package com.sswebtricks.sanjeev.autocompletelocation; import android.content.Context; import android.widget.ArrayAdapter; import android.widget.Filter; import android.widget.Filterable; import java.util.ArrayList; /** * Created by sanjeev on 4/2/18. */ public class LocationAdapter extends ArrayAdapterimplements Filterable { ArrayList resultList; Context mContext; int mResource; LocationModel mPlaceAPI = new LocationModel(); public LocationAdapter(Context context, int resource) { super(context, resource); mContext = context; mResource = resource; } @Override public int getCount() { return resultList.size(); } @Override public String getItem(int position) { return resultList.get(position); } @Override public Filter getFilter() { Filter filter = new Filter() { @Override protected FilterResults performFiltering(CharSequence constraint) { FilterResults filterResults = new FilterResults(); if (constraint != null) { resultList = mPlaceAPI.autocomplete(constraint.toString()); 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; } }
Now MainActivity.java Code :
package com.sswebtricks.sanjeev.autocompletelocation;
import android.app.ProgressDialog;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AutoCompleteTextView;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.RequestQueue;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.net.URLEncoder;
public class MainActivity extends AppCompatActivity {
private ProgressDialog progressDialog;
TextView tlat;
TextView tlong;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tlat=(TextView)findViewById(R.id.lat);
tlong=(TextView)findViewById(R.id.lng);
progressDialog=new ProgressDialog(this);
AutoCompleteTextView autocompleteView = (AutoCompleteTextView)findViewById(R.id.autocomplete);
autocompleteView.setAdapter(new LocationAdapter(getApplicationContext(), R.layout.list_item));
autocompleteView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView parent, View view, int position, long id) {
String description = (String) parent.getItemAtPosition(position);
FindLatLong(description);
Toast.makeText(getApplicationContext(), description, Toast.LENGTH_SHORT).show();
}
});
}
private void FindLatLong(String description) {
progressDialog.setMessage("Fetching Details..");
progressDialog.setCancelable(false);
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progressDialog.show();
RequestQueue queue = Volley.newRequestQueue(getApplicationContext());
String url = Uri.parse("https://maps.googleapis.com/maps/api/geocode/json")
.buildUpon()
.appendQueryParameter("key"Your API KEY")
.appendQueryParameter("address", URLEncoder.encode(description))
.build().toString();
StringRequest sr = new StringRequest(com.android.volley.Request.Method.GET, url, new com.android.volley.Response.Listener() {
@Override
public void onResponse(String response) {
progressDialog.dismiss();
try {
JSONObject jsonObj = new JSONObject(response);
if(jsonObj.getJSONArray("results")!=null) {
JSONArray destination_addresses = jsonObj.getJSONArray("results");
JSONObject geometry= (JSONObject) destination_addresses.get(0);
String lat=String.format("%.4f",geometry.getJSONObject("geometry").getJSONObject("location").getDouble("lat"));
String lng=String.format("%.4f",geometry.getJSONObject("geometry").getJSONObject("location").getDouble("lng"));
Log.d("element", response.toString());
tlat.setText("Lat : "+lat);
tlong.setText("Long : "+lng);
}
else{
Toast.makeText(MainActivity.this, "Error in finding ", Toast.LENGTH_SHORT).show();
progressDialog.dismiss();
}
} catch (JSONException e) {
e.printStackTrace();
progressDialog.dismiss();
}
Log.d("Response", response);
}
}, new com.android.volley.Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
progressDialog.dismiss();
Log.d("Errors", String.valueOf(error));
}
});
queue.add(sr);
sr.setRetryPolicy(new DefaultRetryPolicy(
20000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
}
}














No comments:
Post a Comment