【问题标题】:INVALID API KEY android Google Places无效的 API 密钥 android Google Places
【发布时间】:2015-12-09 04:15:04
【问题描述】:

我已经完成了所有可以搜索的解决方案。我启用了与我的项目相关的 API,并缓慢地制作了 API 密钥(浏览器、Android),但肯定没有一个在工作。根据this,我的 API 密钥格式错误或丢失。有没有办法在我运行项目时检查清单中的值是否正在更改或变为 null?

【问题讨论】:

  • 您是复制并粘贴您的 API 密钥还是根据视觉输入它们?我之所以问,是因为根据我的经验,我发现从开发仪表板复制和粘贴 api 密钥每次都有效。
  • 我尝试了复制粘贴和打字,但还是不行。感谢您的建议,我会再试一次。

标签: android google-places-api api-key google-places


【解决方案1】:

如果您已完成 Google 设置,那么只需尝试使用此网址,它总是对我有用...

private String getPlacesApiUrl() {
    String url = "";
    String location = String.valueOf(currentLocation.latitude)+","+String.valueOf(currentLocation.longitude);       
    String radius = "5000";
    String type = "hospital";       
    String sensor = "false";
    String key = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";

    try {
        url = "https://maps.googleapis.com/maps/api/place/search/json"
            + "?location=" +  URLEncoder.encode(location, "UTF-8")
            + "&type=" + URLEncoder.encode(type, "UTF-8")
            + "&radius=" + URLEncoder.encode(radius, "UTF-8")
            + "&sensor=" + URLEncoder.encode(sensor, "UTF-8")
            + "&key=" + URLEncoder.encode(key, "UTF-8");
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }
    Log.d("url",url);
    return url;
}

但请确保您使用的是浏览器密钥

祝你好运。

【讨论】:

【解决方案2】:

我使用从教程中找到的代码解决了这个问题。希望对遇到同样问题的人有所帮助。

我做了一个 PlaceAPI 类

public class PlaceAPI{

    private static final String TAG = PlaceAPI.class.getSimpleName();

    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 = "key here";

    public ArrayList<String> autocomplete (String input) {
        ArrayList<String> resultList = null;
        ArrayList<String> resultListid = 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.trim());
            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 {
            // Log.d(TAG, jsonResults.toString());

            // Create a JSON object hierarchy from the results
            JSONObject jsonObj = new JSONObject(jsonResults.toString());
            JSONArray predsJsonArray = jsonObj.getJSONArray("predictions");//result

            // 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"));//geometry
            }
        } catch (JSONException e) {
            Log.e(TAG, "Cannot process JSON results", e);
        }

        //GET PLACEID
        try {

            // Create a JSON object hierarchy from the results
            JSONObject jsonObjid = new JSONObject(jsonResults.toString());
            JSONArray predsJsonArrayid = jsonObjid.getJSONArray("predictions");

            // Extract the Place descriptions from the results
            resultListid = new ArrayList<String>(predsJsonArrayid.length());
            for (int i = 0; i < predsJsonArrayid.length(); i++) {
                resultListid.add(predsJsonArrayid.getJSONObject(i).getString("id"));
            }
        } catch (JSONException e) {
            Log.e(TAG, "Cannot process JSON results", e);
        }

        return resultList;
    }
}

并制作了一个适配器 PlacesAutoCompleteAdapter

class PlacesAutoCompleteAdapter extends ArrayAdapter<String> implements Filterable {

    ArrayList<String> resultList;

    Context mContext;
    int mResource;

    PlaceAPI mPlaceAPI = new PlaceAPI();

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

        mContext = context;
        mResource = resource;
    }

    @Override
    public int getCount() {
        // Last item will be the footer
        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;
    }
}

然后在自动完成中使用适配器:

autocomplete = (AutoCompleteTextView) findViewById(R.id.autocomplete);
        autocomplete.setAdapter(new PlacesAutoCompleteAdapter(this, R.layout.autocomplete_list_item));
        autocomplete.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                // Get data associated with the specified position
                // in the list (AdapterView)
                place = (String) parent.getItemAtPosition(position);
                //Toast.makeText(this, description, Toast.LENGTH_SHORT).show();
            }
        });

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-30
    • 1970-01-01
    • 1970-01-01
    • 2014-05-19
    • 1970-01-01
    • 2013-09-09
    • 1970-01-01
    相关资源
    最近更新 更多