Search code examples
androidgoogle-mapsandroid-layoutandroid-studioandroid-maps-utils

how to use xml layout as cluster marker Android


I have a question, Is it possible to set a layout with multi imageviews and textviews as a cluster marker on the google map by android map utils? and how? if somebody provide an good example it would be great this an example of what i want to do:

enter image description here

thanks


Solution

  • I don't know if there is an easier way than what I used that was a year a go this method takes a lot of time if the data set is big so use it on small data set or talk to the designer for other options.

    you can create a layout with what you want the get the bitmap of this layout this add the bitmap as a marker to the map since add marker only takes images. *you need to set the data before creating the bitmap

    first step inflate and set data to your layout

    View marker = ((LayoutInflater) getActivity()
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE))
                    .inflate(R.layout.marker_layout, null);
    

    second get the bitmap from this view

    Bitmap bitmap = createDrawableFromView(
                                    getActivity(), marker);
    

    third add the bitmap as a marker

       MarkerOptions mo = new MarkerOptions().position(
                                        new LatLng(lat, lng))
                                        // .title(address)
                                        .snippet(i + "")
                                        .icon(BitmapDescriptorFactory
                                                .fromBitmap(bitmap));
                                Marker customMarker = googleMap.addMarker(mo);
    

    this is how to get the bitmap

    public static Bitmap createDrawableFromView(Context context, View view) {
        DisplayMetrics displayMetrics = new DisplayMetrics();
        if (context != null) {
            ((Activity) context).getWindowManager().getDefaultDisplay()
                    .getMetrics(displayMetrics);
            view.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,
                    LayoutParams.WRAP_CONTENT));
            view.measure(displayMetrics.widthPixels, displayMetrics.heightPixels);
            view.layout(0, 0, displayMetrics.widthPixels,
                    displayMetrics.heightPixels);
            view.buildDrawingCache();
            Bitmap bitmap = Bitmap.createBitmap(view.getMeasuredWidth(),
                    view.getMeasuredHeight(), Bitmap.Config.ARGB_8888);
    
            Canvas canvas = new Canvas(bitmap);
            view.draw(canvas);
            return bitmap;
        }
        return null;
    }
    

    goodluck with that it was a lot of pain.