我遇到了一个问题,我需要从一个地址中获取经度/纬度,该地址会传递到检索Google静态地图的AsyncTask。
此AsyncTask可以采用一组坐标并创建地图,也可以使用Google Places API检索地址。
我遇到的问题是我不知道如何检索传入的地址的坐标。有没有人知道我可以获得Long / Lat的方式?我弄清楚如何做到这一点的唯一方法是使用另一个AsyncTask。我宁愿不提出2个请求。
创建静态地图 class CreateStaticMapAsyncTask扩展了AsyncTask {
private static final String STATIC_MAPS_API_BASE = "https://maps.googleapis.com/maps/api/staticmap";
private static final String STATIC_MAPS_API_SIZE = "300x300";
@Override
protected void onPreExecute() {
addTask(); // adds one to task count.
super.onPreExecute();
}
@Override
protected Bitmap doInBackground(String... params) {
// TODO Auto-generated method stub
locationString = params[0];
Log.e("LOCATION STRING", locationString);
Bitmap bmp = null;
StringBuilder sb = new StringBuilder(STATIC_MAPS_API_BASE);
try {
sb.append("?center=").append(
URLEncoder.encode(locationString, "UTF-8"));
} catch (UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
sb.append("&size=" + STATIC_MAPS_API_SIZE);
sb.append("&key=" + API_KEY);
String url = new String(sb.toString());
Log.e("URL", sb.toString());
HttpClient httpclient = new DefaultHttpClient();
HttpGet request = new HttpGet(url);
InputStream in = null;
try {
in = httpclient.execute(request).getEntity().getContent();
bmp = BitmapFactory.decodeStream(in);
in.close();
} catch (Exception e) {
e.printStackTrace();
}
return bmp;
}
protected void onPostExecute(Bitmap bmp) {
super.onPostExecute(bmp);
if (bmp != null) {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
data = stream.toByteArray();
removeTask();
// allTasksComplete();
}
}
}
答案 0 :(得分:0)
您需要Geocoder
课程。
用于处理地理编码和反向地理编码的类。地理编码是 转换街道地址或其他描述的过程 位置(纬度,经度)坐标。
如果您查看the example,您会看到后台线程中使用了Geocoder
。由于您已经拥有AsyncTask
,因此您可以将代码添加到doInBackground()
本身。需要修改该示例,因为您需要来自地址的纬度和经度,而不是相反。
您需要getFromLocationName()
方法:
返回已知用于描述命名的地址数组 位置,可能是地名,如" Dalvik,Iceland",an 地址如" 1600 Amphitheatre Parkway,Mountain View,CA",an 机场代码如" SFO"等。返回的地址将是 本地化为提供给此类的构造函数的语言环境。
然后,从Address
对象,您可以获得纬度和经度。