简体   繁体   English

无效的 API 密钥 android Google 地方信息

[英]INVALID API KEY android Google Places

I've done all solutions that I can search.我已经完成了我可以搜索的所有解决方案。 I enabled APIs that are related to my project and made API keys(browser,android) slowly, and surely but not one is working.我启用了与我的项目相关的 API 并缓慢地制作了 API 密钥(浏览器、android),当然但没有一个正在工作。 According to this that my API key is malformed or missing.根据这个,我的API密钥格式不正确或丢失。 Is there a way to check if the value in my manifest is changing or getting null when I run my project?当我运行我的项目时,有没有办法检查我的清单中的值是否正在更改或变为空?

If you are done with Google Setup then just try with this url, It's always working for me...如果您已完成 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;
}

But make sure you are using Browser Key但请确保您使用的是浏览器密钥

Best of luck.祝你好运。

I solved the problem by using a code that i found from tutorials.我使用从教程中找到的代码解决了这个问题。 hope this help for the people having the same trouble.希望这对有同样问题的人有所帮助。

I made a PlaceAPI class我做了一个 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;
    }
}

and made an adapter PlacesAutoCompleteAdapter并制作了一个适配器 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;
    }
}

then using the adapter in autocomplete:然后在自动完成中使用适配器:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM