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

0

I am using the following code from the Google Maps API v2 documentation 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)));

It worked very well for .PNG images, but in my APP I'm only using .SVG icons and images created by the Android Studio 3 Vector Asset itself , and I would like to keep this pattern throughout the application, but I can not get addMarker to accept my .SVG files ...

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 get a .svg file from the res / drawable directories and include as a parameter the icon () method of the MarkerOptions class () from Google Maps API v2 for Android, please only respond if the solution is for that use.

If possible, do a test by creating any .svg icon in the Android Studio Vector Asset and include that file as an icon in MarkerOptions, if it works there on your Maps, you have the solution I'm looking for.

Note:

  • My SVGs have been created correctly and are all functional, no problem in svg files.
  • I'm following this Google Maps Documentation Guide
  • Map activity is functional with standard Bitmap (PNG) icons.
  • The tests are being done on a Samsung Tablet (physical device) 7 "with Android version 4.4.4 SDK 19.
asked by anonymous 28.01.2018 / 19:36

1 answer

0

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 a VectorDrawable (SVG).

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

    
28.01.2018 / 23:26