Skip to content

Instantly share code, notes, and snippets.

@Ozius
Last active October 25, 2023 00:46
Show Gist options
  • Save Ozius/1ef2151908c701854736 to your computer and use it in GitHub Desktop.
Save Ozius/1ef2151908c701854736 to your computer and use it in GitHub Desktop.
Get BitmapDescriptor from a VectorDrawable resource for use as an icon on a Google Map Marker. Google Maps SDK for Android.
/*
mMap.addMarker(new MarkerOptions()
.position(new LatLng(latitude, longitude))
.title("Marker Title")
.snippet("Marker snippet")
.icon(getBitmapDescriptor(R.drawable.ic_place_black_48dp)));
*/
private BitmapDescriptor getBitmapDescriptor(int id) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
VectorDrawable vectorDrawable = (VectorDrawable) getDrawable(id);
int h = vectorDrawable.getIntrinsicHeight();
int w = vectorDrawable.getIntrinsicWidth();
vectorDrawable.setBounds(0, 0, w, h);
Bitmap bm = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bm);
vectorDrawable.draw(canvas);
return BitmapDescriptorFactory.fromBitmap(bm);
} else {
return BitmapDescriptorFactory.fromResource(id);
}
}
Copy link

ghost commented Jul 31, 2018

nice, thanks

@omprakashgupta
Copy link

nice one, it helped me a lot. thanks and keep it up.

@CoolMind
Copy link

CoolMind commented May 7, 2019

On API 19 emulator it throws exception: "Caused by: java.lang.NullPointerException: IBitmapDescriptorFactory is not initialized". I think this is because the emulator doesn't contain Google Play Services. So call this method inside onMapReady(), not onCreateView().

@FredyH4723
Copy link

excellent!

@phileo
Copy link

phileo commented Oct 23, 2023

Kotlin version updated to support calling from anywhere:

fun bitmapDescriptorFromVector(fragmentContext: Context, vectorResId: Int): BitmapDescriptor? =
        // Some VectorDrawables do not display when using ContextCompat.
        // Either ResourcesCompat or VectorDrawableCompat seem to work.
        // VectorDrawableCompat was chosen because it is backed by ResourcesCompat under the hood
       VectorDrawableCompat.create(fragmentContext.resources, vectorResId, fragmentContext.theme)?.run {
            setBounds(0, 0, intrinsicWidth, intrinsicHeight)
            val bitmap = Bitmap.createBitmap(intrinsicWidth, intrinsicHeight, Bitmap.Config.ARGB_8888)
            draw(Canvas(bitmap))
            BitmapDescriptorFactory.fromBitmap(bitmap)
       }
       

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment