androidxamarinxamarin.androidgmsmapview

GoogleMaps marker OnClick - Xamarin


Hi everyone I am using the GoogleMaps Gms.Maps class to show a map on my app (Xamarin.Android).

I am trying to make it so when you click on a marker it will take you to a specific page on my mobile app. however it seems the markers already have on click functions that centre it and display the title. I haven't created this and also can't find it (see below) enter image description here

enter image description here

any idea how I would edit this function or create a new one?

thanks,


Solution

  • Implement Android.Gms.Maps.GoogleMap.IOnMarkerClickListener on your Activity, Fragment or in a separate class and assign that to the GoogleMap instance via the SetOnMarkerClickListener method.

    Example:

    public class MyMarkerClickListener : Java.Lang.Object, IOnMarkerClickListener
    {
        Context context;
        public MyMarkerClickListener(Context context)
        {
            this.context = context;
        }
    
        public bool OnMarkerClick(Marker marker)
        {
            Toast.MakeText(context, $"{marker.Title} was tapped", ToastLength.Long).Show();
            return true;
        }
    }
    

    Usage:

    googleMap.SetOnMarkerClickListener(new MyMarkerClickListener(this));
    

    Note: Normally the listener would be assigned in the OnMapReady callback

    Google Docs: GoogleMap.OnMarkerClickListener

    Returns: true if the listener has consumed the event (i.e., the default behavior should not occur); false otherwise (i.e., the default behavior should occur). The default behavior is for the camera to move to the marker and an info window to appear.