public class AsyncRouteGetter extends AsyncTask<Double, String, String> {
protected String doInBackground(Double... coords) {
String xml = "";
String url = "http://maps.google.com/maps/api/geocode/xml?address=" + coords[0] + "," + coords[1] + "&sensor=false";
//String url = "http://maps.google.com/maps/api/geocode/json?address=51.0031761,17.0499418&sensor=false";
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
xml = EntityUtils.toString(httpEntity);
} catch (Exception e) { e.printStackTrace(); }
//Log.d("LOK", xml);
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = null;
Document doc = null;
try {
builder = factory.newDocumentBuilder();
InputSource is = new InputSource(new StringReader(xml));
doc = builder.parse(is);
} catch (Exception e) { Log.d("DOC", "BLAD2"); e.printStackTrace(); return null; }
String result = doc.getElementsByTagName("formatted_address").item(0).getTextContent();
Log.d("LOKALIZACJA", result);
return result;
}
}
这对我来说非常有效。随意将此标记为答案:)
更新
AsyncRouteGetter arg = new AsyncRouteGetter();
arg.execute(location.latitude, location.longitude);
String route = null;
try {
route = arg.get();
} catch (Exception e) { Log.d("LOK", "Error1"); }
if (route != null) {
Log.d("LOK", route);
currentAddress = route;
} else {
Log.d("LOK", "Error2");
currentAddress = "anything, so you wont work with null";
}