Xamarin Form Custom Map - Unable to navigate to another page in my app

258 views Asked by At

I have a requirement where I need to navigate to another Activity or page created in my core project of my PCL app. All the sample I checked takes me to a website using the URI. What should i change in the code below that will allow me to navigate to different pages in my app when the pin is clicked?

public class CustomMapRenderer : MapRenderer, GoogleMap.IInfoWindowAdapter
{
    ...

    void OnInfoWindowClick(object sender, GoogleMap.InfoWindowClickEventArgs e)
    {
        var url = Android.Net.Uri.Parse(customPin.Url);
        var intent = new Intent(Intent.ActionView, url);
        intent.AddFlags(ActivityFlags.NewTask);
        Android.App.Application.Context.StartActivity(intent);
    }
}
2

There are 2 answers

0
Steve Chadbourne On

You generally call back to your custom map in the PCL and let it handle the navigation.

The way I do it is by:

1) Add a bindable property of type ICommand to the custom map

   public static readonly BindableProperty MapClickedCommandProperty = BindableProperty.Create(
        nameof(MapClickedCommand),
        typeof(ICommand),
        typeof(CustomMap));

    public ICommand MapClickedCommand
    {
        get { return (ICommand)GetValue(MapClickedCommandProperty); }
        set { SetValue(MapClickedCommandProperty, value); }
    }

2) Add a public method to the custom map that will be called by the custom renderer

public void RaiseMapClicked(Url url)
{
    MapClickedCommand?.Execute(url);
}

3) In the custom renderer in your OnInfoWindowClick call the public method

var url = Android.Net.Uri.Parse(customPin.Url);
var formsMap = Element as CustomMap;
formsMap.RaiseMapClicked(url);

This allows you to bind a command to the custom map and handle the Url in your view model.

0
David Conlisk On

You can send a message from your custom MapRenderer whenever a pin is clicked using the Xamarin MessagingCenter. See my answer to a similar question here.