I am running into an issue where I need to get the Longitude / Latitude from an address that is passed into an AsyncTask that retrieves a Google Static Map.
This AsyncTask can take a set of coordinates and create a map, and it can also take an address that is retrieved using Google Places API.
The issue I am having is that I don't know how I can retrieve the coordinates of the address that is passed in. Does anyone know a way that I can get the Long/Lat? The only way I have figured out how to do it is by using another AsyncTask. I would rather not make 2 requests though.
CREATE STATIC MAP class CreateStaticMapAsyncTask extends 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();
}
}
}
You need the
Geocoder
class.If you go over the example, you will see that
Geocoder
is used in a background thread. Since you already have anAsyncTask
, you can add the code todoInBackground()
itself. The example will need to be modified because you need a latitude and longitude from address and not the other way around.You will need the
getFromLocationName()
method:Then from the
Address
object, you can get the latitude and longitude.