Google Map Api Places AutoComplete Implementation in Android

Google Map Api Places AutoComplete Implementation : -

1)Create Google Map Api key from : -

https://console.developers.google.com/apis/credentials
->Select The Project
->Create Credentials
->Select API key

The API Key is Generated : -
Its Looks Like : - AIz****O_AamI*******rBC_hL*******BU

2)Now Select Map Api For Places : -

->From Home Select Api & Services.
->Select Library : -
->Enable Places Sdk For Android
->Enable Places Api
Now the api generated For Searching is : -
->https://maps.googleapis.com/maps/api/place/autocomplete/json?components=country:in&input=gandhidham&key=AIz****O_AamI*******rBC_hL*******BU

Change you api key.

Ex From : -https://examples.javacodegeeks.com/android/android-google-places-autocomplete-api-example/

3)Now Come back in Android Studio : -
1)->In activity_main.xml
Add this : -
<?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">
 <AutoCompleteTextView
                    android:id="@+id/autoCompleteTextView"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:ems="10"
                    android:textColorHint="@color/colorWhite"
                    android:hint="Please enter your city"
                    android:textColor="@color/colorWhite">
</AutoCompleteTextView>
</RelativeLayout>

2)->Create one raw file for display data : -
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:text="Ahmedabad"
    android:fontFamily="@font/opensans_regular"
    android:textAppearance="@style/TextAppearance.AppCompat.Medium"
    android:padding="@dimen/medium_margin"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">
</TextView>

3)->Add In Mainactivity.java
public class Mainactivity extends Activity implements OnItemClickListener {

private static final String LOG_TAG = "Google Places Autocomplete";
    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 here -------";
   
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        AutoCompleteTextView autoCompView = (AutoCompleteTextView) findViewById(R.id.autoCompleteTextView);
        autoCompView.setAdapter(new GooglePlacesAutocompleteAdapter(this, R.layout.list_item));
        autoCompView.setOnItemClickListener(this);
    }
   
    public void onItemClick(AdapterView adapterView, View view, int position, long id) {
       Thread thread = new Thread(new Runnable() {

                    @Override
                    public void run() {
                        try  {
                            googlePlacesAutocompleteAdapter.getLatLong(position);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                });
        String str = (String) adapterView.getItemAtPosition(position);
        Toast.makeText(this, str, Toast.LENGTH_SHORT).show();
         String Lattitude = googlePlacesAutocompleteAdapter.get_lat();
         String Longtitude = googlePlacesAutocompleteAdapter.get_long();
    }
}

4)-->Add Adapter
package com.demo.adapter;

import android.annotation.SuppressLint;
import android.content.Context;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.Filter;
import android.widget.Filterable;

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;

package com.fotu_votu.adapter;

import android.annotation.SuppressLint;
import android.content.Context;
import android.os.StrictMode;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.Filter;
import android.widget.Filterable;

import com.fotu_votu.Utils.Constants;

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;


public class GooglePlacesAutocompleteAdapter extends ArrayAdapter implements Filterable {

    private ArrayList resultList;
    private static ArrayList placeIdList;
    private static String latitude = "0", longitude = "0";

    public GooglePlacesAutocompleteAdapter(Context context, int textViewResourceId) {
        super(context, textViewResourceId);
    }

    @Override

    public int getCount() {
        return resultList.size();
    }

    @Override
    public String getItem(int index) {
        return String.valueOf(resultList.get(index));
    }

    @SuppressLint("LongLogTag")
    public void getLatLong(int position) {
        HttpURLConnection conn1 = null;
        InputStreamReader in1;

        String placeid = placeIdList.get(position).toString();
        StringBuilder jsonResults = new StringBuilder();
        if (placeid != null && !placeid.equalsIgnoreCase("0")) {

            try {
                StringBuilder sb = new StringBuilder(Constants.PLACES_API_BASE + Constants.GET_LAT_LANG + Constants.OUT_JSON);
                sb.append("?placeid=" + URLEncoder.encode(placeid, "utf8"));
                sb.append("&key=" + Constants.API_KEY);
                URL url = new URL(sb.toString());
                conn1 = (HttpURLConnection) url.openConnection();
                in1 = new InputStreamReader(conn1.getInputStream());

                // Load the results into a StringBuilder
                int read;
                char[] buff = new char[1024];
                while ((read = in1.read(buff)) != -1) {
                    jsonResults.append(buff, 0, read);
                }
            } catch (MalformedURLException e) {
                Log.e(Constants.LOG_TAG, "Error processing Places API URL", e);
            } catch (IOException e) {
                Log.e(Constants.LOG_TAG, "Error connecting to Places API", e);
            } finally {
                if (conn1 != null) {
                    conn1.disconnect();
                }
            }
            try {
                // Create a JSON object hierarchy from the results
                JSONObject jsonObj = new JSONObject(jsonResults.toString());

                // Extract the Place descriptions from the results
                latitude = String.valueOf(jsonObj.getJSONObject("result.geometry.location.lat"));
                longitude = String.valueOf(jsonObj.getJSONObject("result.geometry.location.lng"));
            } catch (JSONException e) {
                Log.e(Constants.LOG_TAG, "Cannot process JSON results", e);
            }
        }
    }

    public String get_lat() {
        return latitude;
    }

    public String get_long() {
        return longitude;
    }

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

    @SuppressLint("LongLogTag")
    public static ArrayList autocomplete(String input) {
        HttpURLConnection conn = null;
        InputStreamReader in;
        ArrayList resultList = null;
        StringBuilder jsonResults = new StringBuilder();

        try {
            StringBuilder sb = new StringBuilder(Constants.PLACES_API_BASE + Constants.TYPE_AUTOCOMPLETE + Constants.OUT_JSON);
            sb.append("?key=" + Constants.API_KEY);
            sb.append("&components=country:in");
            sb.append("&input=" + URLEncoder.encode(input, "utf8"));

            URL url = new URL(sb.toString());
            conn = (HttpURLConnection) url.openConnection();
            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(Constants.LOG_TAG, "Error processing Places API URL", e);
            return resultList;
        } catch (IOException e) {
            Log.e(Constants.LOG_TAG, "Error connecting to Places API", e);
            return resultList;
        } finally {
            if (conn != null) {
                conn.disconnect();
            }
        }
        try {
            // Create a JSON object hierarchy from the results
            JSONObject jsonObj = new JSONObject(jsonResults.toString());
            JSONArray predsJsonArray = jsonObj.getJSONArray("predictions");

            // Extract the Place descriptions from the results
            resultList = new ArrayList(predsJsonArray.length());
            placeIdList = new ArrayList(predsJsonArray.length());
            for (int i = 0; i < predsJsonArray.length(); i++) {
                System.out.println(predsJsonArray.getJSONObject(i).getString("description"));
                System.out.println("============================================================");
                resultList.add(predsJsonArray.getJSONObject(i).getString("description"));
                placeIdList.add(predsJsonArray.getJSONObject(i).getString("place_id"));
            }
        } catch (JSONException e) {
            Log.e(Constants.LOG_TAG, "Cannot process JSON results", e);
        }
        return resultList;
    }

}

Comments

Popular posts from this blog

How to Fix ‘This file name is too long’ Error?

General Knowledge