Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android Google Maps Marker: Released unknown imageData reference

I'm trying to add support to tablets in my app and run into IllegalArgumentException thrown by this line of code:

marker.setIcon(BitmapDescriptorFactory.fromResource(R.drawable.arrow_green_10by19))

The method .fromResource works fine with the R.drawable.arrow_green_10by19 from an image file (png) but when the png is replaced with the vector file arrow_green_10by19.xml (which renders fine in the Android Studio IDE) it generates a runtime as mentioned.

Does anybody knows how to implement a vector resource in the BitmapDescriptorFactory and could help me out?

Thanks.

like image 630
Walter Roncada Avatar asked Oct 25 '15 03:10

Walter Roncada


1 Answers

I had the same problem but I realized that on my device with API 16 it works fine but with API 21 it crashes. Finally it works in both devices using this solution. Here the code:

@TargetApi(Build.VERSION_CODES.LOLLIPOP)
private static Bitmap getBitmap(VectorDrawable vectorDrawable) {
    Bitmap bitmap = Bitmap.createBitmap(vectorDrawable.getIntrinsicWidth(),
            vectorDrawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
    Canvas canvas = new Canvas(bitmap);
    vectorDrawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
    vectorDrawable.draw(canvas);
    return bitmap;
}

and this:

private static Bitmap getBitmap(Context context, int drawableId) {
    Drawable drawable = ContextCompat.getDrawable(context, drawableId);
    if (drawable instanceof BitmapDrawable) {
        return BitmapFactory.decodeResource(context.getResources(), drawableId);
    } else if (drawable instanceof VectorDrawable) {
        return getBitmap((VectorDrawable) drawable);
    } else {
        throw new IllegalArgumentException("unsupported drawable type");
    }
}

So I combined those 2 functions in this way:

private Marker addMark(LatLng latLng, String title) {
    Bitmap bitmap = getBitmap(getContext(), R.drawable.ic_place_24dp);
    Marker marker = googleMap.addMarker(new MarkerOptions().position(latLng)
            .title(title)
            .icon(BitmapDescriptorFactory.fromBitmap(bitmap))
            .draggable(true));

    return marker;
}

Where R.drawable.ic_place_24dp is a vector asset (.xml), not a .png

like image 187
Miguel Garcia Avatar answered Nov 10 '22 00:11

Miguel Garcia