androidandroid-mapviewandroid-overlay

Loading ItemizedOverlays markers from the web


I was wondering what is the proper way of loading ItemizedOverlay markers from the web, use caching in some sort of a way.

Right now i'm downloading all the images and converting them to drawables, it works just fine but I want to see if there is a better way of doing this.

public class ImageLoad extends AsyncTask<String, Bitmap, Bitmap> {
private String url;
private MapView mapView;

public ImageLoad() {
}

public ImageLoad(MapView mapView) {
    this.mapView = mapView;
}

protected Bitmap doInBackground(String... params) {
    url = params[0];
    try {
        return BitmapFactory.decodeStream(new URL(url).openConnection().getInputStream());
    } catch (MalformedURLException e) {
        e.printStackTrace();
        return null;
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }
}

@Override
protected void onPostExecute(Bitmap result) {
    Drawable d = new BitmapDrawable(mapView.getContext().getResources(), result);
    SimpleItemizedOverlay itemizedOverlay = new SimpleItemizedOverlay(d, mapView);
    GeoPoint p = new GeoPoint(32061628, 34774767);
    itemizedOverlay.addOverlay(new OverlayItem(p, "zzz", "zzz"));
    mapView.getOverlays().add(itemizedOverlay);
    mapView.invalidate();
    super.onPostExecute(result);
}
}

Solution

  • The overall approach is correct, but the details how you implemented it can be improved.

    Improvement 1

    In your onPostExecute() every time you download an image you are creating a new ItemizedOverlay object and add a single item to it. In general, is more efficient to use a unique ItemizedOverlay and add all the items to it.

    With this, you will have only one ItemizedOverlay with several items in it. With your code you have several ItemizedOverlays with one image each.

    Improvement 2

    You are not resizing the images that you download the Web. Unless you are sure they all have a suitable size, you should enforce the size before add them to the overlay. Otherwise, you will be using more memory and could get an image that covers all the screen and thats not what user expects.

    You can resize the Bitmap using method Bitmap.createScaledBitmap().

    Regards.