我知道这是一个老问题。但我希望它将来对其他人有用。
首先,您必须将其添加到您的模块级别build.gradle,
android {
useLibrary 'org.apache.http.legacy'
}
下一步是创建一个 AsyncTask,
public class MyAsyncTask extends AsyncTask<String, Void, Boolean> {
private JSONObject jsonObject;
@Override
protected void onPostExecute(Boolean aBoolean) {
super.onPostExecute(aBoolean);
System.out.println(jsonObject); //use jsonObject here
}
protected Boolean doInBackground(final String... args) {
try {
Looper.prepare();
String latitude = args[0];
String longitude = args[1];
String radius = args[2];
String name = args[3];
String key = "YOUR_API_KEY_FOR_BROWSER";
String uri = "https://maps.googleapis.com/maps/api/place/nearbysearch/json?"
+ "location=" + latitude + "," + longitude
+ "&radius=" + radius
+ "&name=" + name
+ "&key="+ key; // you can add more options here
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(uri);
httpPost.setEntity(new UrlEncodedFormEntity(new ArrayList<NameValuePair>()));
HttpEntity httpEntity = httpClient.execute(httpPost).getEntity();
InputStream stream = httpEntity.getContent();
BufferedReader bReader = new BufferedReader(new InputStreamReader(stream, "utf-8"), 8);
StringBuilder sBuilder = new StringBuilder();
String line = null;
while ((line = bReader.readLine()) != null) {
sBuilder.append(line + "\n");
}
stream.close();
jsonObject = new JSONObject(sBuilder.toString());
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
然后从任何你想要的地方执行 AsyncTask。 (可能来自 MainActivity),
String latitude = String.valueOf(latLng.latitude);
String longitude = String.valueOf(latLng.longitude);
String radius = "2000"; // 2 Kilometer
String name = "hospital";
MyAsyncTask myAsyncTask = new MyAsyncTask();
myAsyncTask.execute(latitude, longitude, radius, name);
您可以在从 Google 地方信息获取地点时添加更多选项,例如 关键字、语言 等。阅读更多关于这些选项以及如何使用它们的信息here。