谷歌放置API - V2-自动完成不会显示所有的地方结果

时间:2014-09-25 04:32:38

标签: android google-places-api google-maps-api-2

我正在尝试按照Android文档,但它并没有向我展示所有的地方建议。例如,如果我写集群Z.这不会向我显示任何建议。正是我想要的是如果我输入位置X2,它应该返回我X1,X2本身,X3,X4,X5,因为我被这些位置包围。我错过了什么?

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";
ArrayList<String> resultList = null;
//API KEY = xxxxxxxxxxxxxxxxxxx; // Enter Your Key

private ArrayList<String> autocomplete(String input) {

    HttpURLConnection conn = null;
    StringBuilder jsonResults = new StringBuilder();
    try {
        StringBuilder sb = new StringBuilder(PLACES_API_BASE + TYPE_AUTOCOMPLETE + OUT_JSON);
        sb.append("?key=" + "Enter Your Key");
        sb.append("&components=country:myCountry");
        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<String>(predsJsonArray.length());
        for (int i = 0; i < predsJsonArray.length(); i++) {
            resultList.add(predsJsonArray.getJSONObject(i).getString("description"));

        }
    } catch (JSONException e) {
        //Log.e(LOG_TAG, "Cannot process JSON results", e);
    }

    Log.v("returnResult",""+resultList.toString());
    return resultList;
}

2 个答案:

答案 0 :(得分:0)

如果要显示Google地图搜索框中显示的所有结果,请尝试使用Google搜索框而不是自动填充

答案 1 :(得分:0)

如果您想用单个库方法调用替换所有代码,可以查看Sprockets(披露:我是开发人员)。相当于:

Places.autocomplete(Params.create().query(input)).getResult()

Places Javadoc

您还可以查看GooglePlaceAutoComplete窗口小部件,它可以为您完成所有操作,并提供用户选择的Place

<net.sf.sprockets.widget.GooglePlaceAutoComplete
    android:id="@+id/place"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"/>

GooglePlaceAutoComplete Javadoc