Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use a view instead of Marker in Google Maps

Its possible to use a custom view instead of a Marker in Google Maps API v2? It's sad that Google doesn't allow us to customize our markers with views (Relative layout with imageviews, textviews etc) , so its possible to inflate a view and then put that view to a specific position in a map?

like image 624
WitaloBenicio Avatar asked Feb 08 '23 15:02

WitaloBenicio


2 Answers

You can use IconGenerator to achieve this.

IconGenerator iconGenerator = new IconGenerator(context);
iconGenerator.setBackground(context.getDrawable(R.drawable.bg_custom_marker));
View inflatedView = View.inflate(context, R.layout.marker_custom, null);
iconGenerator.setContentView(inflatedView);
Marker marker = map.addMarker(
        new MarkerOptions()
                .position(new LatLng(-34.397, 150.644))
                .icon(BitmapDescriptorFactory.fromBitmap(iconGenerator.makeIcon())));

Now we need that marker_custom view and bg_custom_marker drawable.

marker_custom.xml

<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:backgroundTint="@android:color/white"
    tools:ignore="RtlHardcoded">

    <TextView
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="I'm a custom view :)" />

</androidx.constraintlayout.widget.ConstraintLayout>

bg_custom_marker.xml

<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <solid android:color="#000000" />
    <stroke
        android:width="1dp"
        android:color="#FFFFFF" />
    <corners android:radius="5dp" />
    <padding
        android:bottom="5dp"
        android:left="5dp"
        android:right="5dp"
        android:top="5dp" />
</shape>

It looks like the following:

Custom Marker

Edit: iconGenerator.setBackground(null); might be more flexiable.

like image 171
Yunus Emre Avatar answered Feb 13 '23 02:02

Yunus Emre


Well you can not put view on Google Maps but @WitaloBenicio said you can convert that view to Bitmap and show it on marker

SO : Convert View to bitmap

and using BitmapDescriptorFactory.fromBitmap (Bitmap image) add to marker

mMap.addMarker(new MarkerOptions()..icon(BitmapDescriptorFactory.fromBitmap(bitmap)));

I strongly prefer go to this library Google Maps Android API Utility Library and check for IconGenerator class Git Repo

like image 35
Bharatesh Avatar answered Feb 13 '23 04:02

Bharatesh