How to use icon SVG in Google Maps API Android Addmarker (MarkerOptions)

I am using the following example code from the documentation for Google Maps API V2 for Android :

mMap.addMarker(new MarkerOptions()
                .icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_bike))
                .anchor(0.0f, 1.0f) // Anchors the marker on the bottom left
                .position(new LatLng(41.889, -87.622)));

Worked great for images.PNG , but in my APP I'm only using icons and images in .SVG created by Android Studio 3's own Vector Asset, and I would like to maintain this pattern throughout the app, but not be able to make addMarker accept my files .SVG...

I found the following question in StackOverflow in English, but no answer worked for me:

Custom marker in google maps in android with vector asset icon

I need to make it clear, that my need is to take a file .svg directories res / drawable and include as parameter method icon() of Class MarkerOptions() of Google Maps API v2 P/ Android, please only answer if the solution is for this use.

If possible, take a test creating any icon .svg in Vector Asset of Android Studio and include this file as icon in MarkerOptions, if it works ai in your Maps, you have the solution I'm looking for.

Obs:

  • my SVG have been created correctly and are all functional, no problem in svg files.
  • I'm following this Google Maps documentation guide
  • the map activity is functional with Standard Bitmap icons (PNG).
  • the tests are being made on a Samsung 7 " Tablet (physical device) with Android version 4.4.4 SDK 19.
Author: Chinnon Santos, 2018-01-28

1 answers

Write a method to get a bitmapdescriptor

private BitmapDescriptor getBitmapDescriptorFromVectorDrawable(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);
    }
}

Change Your Code to use the method:

mMap.addMarker(new MarkerOptions()
                .icon(getBitmapDescriptorFromVectorDrawable(R.drawable.ic_bike))
                .anchor(0.0f, 1.0f) // Anchors the marker on the bottom left
                .position(new LatLng(41.889, -87.622)));

Note: the id passed to getBitmapDescriptorFromVectorDrawable() must be from a VectorDrawable(SVG).

Source: Get BitmapDescriptor from a VectorDrawable resource for use as an icon on a Google Map Marker.

 1
Author: ramaral, 2018-01-29 15:49:54