2
我正在開發一款應用程序,允許用戶通過實施Google Places API來定位附近的場所。但是,關於如何實現這一點,沒有任何全面的教程/示例。我已經能夠拼湊一些代碼,但我仍然不知道如何解析結果,然後將其顯示在覆蓋層上。任何幫助是極大的讚賞。如何在Android中實現Google Places API?
我正在開發一款應用程序,允許用戶通過實施Google Places API來定位附近的場所。但是,關於如何實現這一點,沒有任何全面的教程/示例。我已經能夠拼湊一些代碼,但我仍然不知道如何解析結果,然後將其顯示在覆蓋層上。任何幫助是極大的讚賞。如何在Android中實現Google Places API?
你知道哪裏更具體的問題在哪裏(解析結果或放置引腳)?你看到什麼類型的錯誤?
爲了解析Places API的結果,有一個在教程: https://developers.google.com/academy/apis/maps/places/autocomplete-android
從教程下面的代碼應該可以幫助您開始使用分析結果。爲自動完成和搜索API返回的JSON類似,但不相同。請務必遵循https://developers.google.com/places/documentation/#PlaceSearchResults的格式。
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 = "YOUR_API_KEY";
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=false&key=" + API_KEY);
sb.append("&components=country:uk");
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);
}
return resultList;
}
你可以看看我的編輯。我不知道我是否正在取得進展,或只是變得更加困惑。 – 2012-08-02 23:03:37