Android Google Maps Marker: Released unknown imageData reference
Asked Answered
C

1

5

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.

Canner answered 25/10, 2015 at 3:0 Comment(0)
R
15

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

Rote answered 22/2, 2016 at 17:5 Comment(3)
Whilst this may theoretically answer the question, it would be preferable to include the essential parts of the answer here, and provide the link for reference.Hysteresis
Thanks, I think it's better now :)Rote
It is way way better now. Thanks for that. And an upvote for the effortHysteresis

© 2022 - 2024 — McMap. All rights reserved.