Cockpit Aliens
Cockpit Aliens

Reputation: 411

Places Google Api - Autocomplete

This is a bit weird, I followed the Google places API to add autocomplete for my android app. Google Places API request denied for Android autocomplete, even with the right api key. I even tried to check with the JSON Client and requested both GET/POST still same error because I'm sure my code follows the integration for google api autocomplete accordingly. I have not found any solution that resolves the error. Some answers suggest removing sensor with place_id. I don't know. Kindly explain a solution or suggestion that would help me to get the autocomplete working fine.

https://maps.googleapis.com/maps/api/place/autocomplete/json/?sensor=false&key=API_KEY&components=country=us&input=california

enter image description here

Upvotes: 0

Views: 1473

Answers (5)

Ravind Maurya
Ravind Maurya

Reputation: 977

Try this url with your api key:

https://maps.googleapis.com/maps/api/place/autocomplete/json?sensor=true&key= api key&language=en&input=kir

Upvotes: 2

Cockpit Aliens
Cockpit Aliens

Reputation: 411

Hey guys now the autocomplete is working Jaswinder I just added place_id where you commented it out and wala! it works like a charm.

Hope this code helps someone. I used the Key for browser application and enabled both Places api and Goople map api in the console.

private class PlacesAutoCompleteAdapter extends ArrayAdapter<String>
        implements Filterable {
    private ArrayList<String> 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;
    }
}

// Get array list of addresses
private ArrayList<String> autocomplete(String input) {

    ArrayList<String> resultList = null;

    HttpURLConnection conn = null;

    StringBuilder jsonResults = new StringBuilder();

    try {
        StringBuilder sb = new StringBuilder(PLACES_API_BASE
                + TYPE_AUTOCOMPLETE + OUT_JSON);

        sb.append("?sensor=true&key="

        + API_KEY);

        // for current country.Get the country code by SIM

        // If you run this in emulator then it will get country name is
        // "us".

        String cName = getCountryCode();

        if (cName != null) {
            countryName = cName;
        } else {
            countryName = "za";
        }
        sb.append("&components=country:" + countryName);
        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(TAG, "Error processing Places API URL", e);

        return resultList;

    } catch (IOException e) {

        Log.e(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<String>(predsJsonArray.length());

        for (int i = 0; i < predsJsonArray.length(); i++) {

            resultList.add(predsJsonArray.getJSONObject(i).getString(

            "description"));

            resultList.add(predsJsonArray.getJSONObject(i).getString(
                    "place_id"));

        }

    } catch (JSONException e) {

        Log.e(TAG, "Cannot process JSON results", e);

    }

    return resultList;

}

}

Upvotes: 0

Jaswinder
Jaswinder

Reputation: 2279

public class PlacesAutoCompleteAdapter extends ArrayAdapter<String> implements
    Filterable {
private ArrayList<MapdataList> resultList;

public PlacesAutoCompleteAdapter(Context context, int textViewResourceId) {
    super(context, textViewResourceId);

}

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

@Override
public String getItem(int index) {

    MapdataList data = resultList.get(index);

    return data.getPlaceName();

}

public String mthod(int index) {
    MapdataList data = resultList.get(index);

    return data.getPlaceID();

}

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

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 = "serverkry";

private ArrayList<MapdataList> autocomplete(String input) {
    ArrayList<MapdataList> 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("&sensor=true");
        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();
        }
    }

    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<MapdataList>(predsJsonArray.length());
        for (int i = 0; i < predsJsonArray.length(); i++) {

            MapdataList mapData = new MapdataList();
            mapData.setPlaceName(predsJsonArray.getJSONObject(i).getString(
                    "description"));
            mapData.setPlaceID(predsJsonArray.getJSONObject(i).getString(
                    "place_id"));

            resultList.add(mapData);

            // resultList.add(predsJsonArray.getJSONObject(i).getString(
            // "description"));
            // resultList.add(1,predsJsonArray.getJSONObject(i).getString(
            // "place_id"));
        }
    } catch (JSONException e) {
        Log.e(LOG_TAG, "Cannot process JSON results", e);
    }

    return resultList;
  }
  }

`

public class TestMapAutocomplete extends Activity {
PlacesAutoCompleteAdapter obj;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_test_map_autocomplete);

    AutoCompleteTextView YY = (AutoCompleteTextView) findViewById(R.id.Google_autoCompleteTextView1);
    obj = new PlacesAutoCompleteAdapter(this, R.layout.google_list_items);
    YY.setAdapter(obj);

    YY.setOnItemClickListener(getPlaceId);

}

public OnItemClickListener getPlaceId = new OnItemClickListener() {

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position,
            long id) {
        // TODO Auto-generated method stub

        // int dd= (Integer) parent.getItemAtPosition(position);
        String mcityselect = obj.mthod(position);
        // String mcityselect = (String) parent.getItemAtPosition(position);
        String mcityccselect = (String) parent.getItemAtPosition(position);

    }
};

  }

its working ... do like this create server key and allow all then in android use autoacmpltere Create a server key in google api console and allow all then enable google feture in permissions its working bro try this ....

Upvotes: 0

Cockpit Aliens
Cockpit Aliens

Reputation: 411

So jaswinder the changes I need to make as I assumed is replace the sensor with place_id and my try catch should also change to look like your code snippet;

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<String>(predsJsonArray.length());

        for (int i = 0; i < predsJsonArray.length(); i++) {

            resultList.add(predsJsonArray.getJSONObject(i).getString(

            "description"));

        }

    } catch (JSONException e) {

        Log.e(TAG, "Cannot process JSON results", e);

    }

    return resultList;

Then I can create server key as you explained, I should be good to go then. Thanks

Upvotes: 0

TechHelper
TechHelper

Reputation: 821

It will work in android app only. Don't try it in REST client. Instead try debugging your app to see response.

Upvotes: 0

Related Questions