How can I use Picasso to add icon to Marker?
Picasso provides a generic Target
interface you can use to implement your own image destination. Specifically, you will want to override onBitmapLoaded
to populate your marker.
A basic implementation is given below.
public class PicassoMarker implements Target {
Marker mMarker;
PicassoMarker(Marker marker) {
mMarker = marker;
}
@Override
public int hashCode() {
return mMarker.hashCode();
}
@Override
public boolean equals(Object o) {
if(o instanceof PicassoMarker) {
Marker marker = ((PicassoMarker) o).mMarker;
return mMarker.equals(marker);
} else {
return false;
}
}
@Override
public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
mMarker.setIcon(BitmapDescriptorFactory.fromBitmap(bitmap));
}
@Override
public void onBitmapFailed(Drawable errorDrawable) {
}
@Override
public void onPrepareLoad(Drawable placeHolderDrawable) {
}
}
You would use it like this --
marker = new PicassoMarker(myMarker);
Picasso.with(MainActivity.this).load(URL).into(marker);
Note Picasso only holds a week reference to the Target
passed to into
. Therefore, the marker
reference needs to exist until the image is loaded to avoid have the callbacks being cleaned up by the garbage collector.