放置Google Api - 自动填充功能

时间:2014-12-09 07:27:59

标签: android json api google-maps autocomplete

这有点奇怪,我按照Google Places API为我的Android应用添加自动完成功能。即使使用正确的API密钥,Google Places API请求也会因Android自动填充而被拒绝。我甚至尝试使用JSON客户端检查并请求两个GET / POST仍然是相同的错误,因为我确定我的代码遵循google api自动完成的集成。我没有找到解决错误的任何解决方案。一些答案建议使用place_id删除传感器。我不知道。请解释一下 一个解决方案或建议,可以帮助我使自动完成工作正常。

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

enter image description here

5 个答案:

答案 0 :(得分:1)

嗨兄弟这样用你的api键试试这个url: https://maps.googleapis.com/maps/api/place/autocomplete/json?sensor=true&key= api key& language = en& input = kir

其工作经纪人。

答案 1 :(得分:0)

它只适用于Android应用程序。不要在REST客户端中尝试它。而是尝试调试您的应用以查看响应。

答案 2 :(得分:0)

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

    }
};

  }

它的工作...这样做创建服务器密钥并允许所有然后在Android中使用autoacmpltere在谷歌api控制台中创建一个服务器密钥并允许所有然后启用权限谷歌的胎儿 它的工作兄弟试试这个......

答案 3 :(得分:0)

所以我需要做的改变是因为我假设用place_id替换传感器,我的try catch也应该改为看起来像你的代码片段;

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;

然后我可以按照你的解释创建服务器密钥,我应该好好去。感谢

答案 4 :(得分:0)

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.

希望此代码可以帮助某人。我使用Key for browser application并在控制台中启用了Places api和Goople map api。

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;

}

}