Custom marker in google maps in android with vector asset icon

前端 未结 9 1210
小鲜肉
小鲜肉 2020-12-02 09:50

How can we achieve a map marker icon with vector asset file, the way google shows it like this, programatically:

Update:

m         


        
9条回答
  •  不知归路
    2020-12-02 10:03

    Might be a bit late to the game but this works great with Google Maps v2:

    public static BitmapDescriptor getBitmapFromVector(@NonNull Context context,
                                                       @DrawableRes int vectorResourceId,
                                                       @ColorInt int tintColor) {
    
        Drawable vectorDrawable = ResourcesCompat.getDrawable(
                context.getResources(), vectorResourceId, null);
        if (vectorDrawable == null) {
            Log.e(TAG, "Requested vector resource was not found");
            return BitmapDescriptorFactory.defaultMarker();
        }
        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());
        DrawableCompat.setTint(vectorDrawable, tintColor);
        vectorDrawable.draw(canvas);
        return BitmapDescriptorFactory.fromBitmap(bitmap);
    }
    

    Initialized as:

    locationMarkerIcon = LayoutUtils.getBitmapFromVector(ctx, R.drawable.ic_location_marker,
                    ContextCompat.getColor(ctx, R.color.marker_color));
    

    Usage:

    googleMap.addMarker(MarkerOptions().icon(getMarkerIcon()).position(latLng));
    

    Note: getMarkerIcon() just returns the initialized non null locationMarkerIcon member variable.

    Screenshot:

提交回复
热议问题