Android Autocomplete Location Search - Supercoders | Web Development and Design | Tutorial for Java, PHP, HTML, Javascript Android Autocomplete Location Search - Supercoders | Web Development and Design | Tutorial for Java, PHP, HTML, Javascript

Breaking

Post Top Ad

Post Top Ad

Sunday, February 4, 2018

Android Autocomplete Location Search

Android Autocomplete Location Search

Android Autocomplete Location Search

  

 

First visit

https://console.developers.google.com/

And Create A New Project And Generate a API key

After That Create A New Android studio Project

Android Autocomplete Location Search


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.

Google location dependency


After that sync now

gradle sync


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>
Now Create a location model for google place api.
Location Model


LocationModel.java



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;
    }
}

Location Model Java

Now come to layout file which is activity_main.xml

activity_main.xml



<?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>

It look like this

activity main layout

activity main layout

Now create a layout resource file for list item

list_item.xml


<?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" />

look like this.

list item



Now create LocationAdapter


LocationAdapter.java

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 ArrayAdapter implements 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));
    }

}

Now Run Your App And Don't Forget To Put Api Key

MainActivity Auto Complete

Android Auto Complete

Android Auto Complete


Download Complete Source Code

No comments:

Post a Comment

Post Top Ad