Search code examples
mapsmauimaui-community-toolkitfromjson

Xamarin.Forms.GoogleMaps.MapStyle.FromJson(styleFile) not working in MAUI


This code was previously used in Xamarin and later migrated to MAUI. After that MAUI is not supporting MapStyle. So here is the code I'm facing the issue.

private void AddMapStyle()
{
    var assembly = typeof(Event).GetTypeInfo().Assembly;
    Stream stream = new MemoryStream();

    if (eventViewModel.IsDark || deviceTheme == AppTheme.Dark)
    {
        stream = assembly.GetManifestResourceStream($"App.Views.Themes.MapDark.json");
    }
    else
    {
        assembly.GetManifestResourceStream($"App.Views.Themes.MapLight.json");
    }
    string styleFile;
    using (var reader = new System.IO.StreamReader(stream))
    {
        styleFile = reader.ReadToEnd();
    }

    map.MapType = Xamarin.Forms.GoogleMaps.MapStyle.FromJson(styleFile);
}

Then the error I'm getting is

Severity    Code    Description Project File    Line    Suppression State
Error   CS0234  The type or namespace name 'Forms' does not exist in the namespace 'Xamarin' (are you missing an assembly reference?)   App.MAUI (net8.0-android34.0), App.MAUI (net8.0-ios)    C:\wwwroot\App.MAUI\Views\Event.xaml.cs 965 Active

So I need a know how to modify this or any suggestion to over come form this issue


Solution

  • In Maui, you could use Handler to customize your own map. Try the code below,

        void ModifyMap()
        {
            ...
            Microsoft.Maui.Maps.Handlers.MapHandler.Mapper.AppendToMapping("MyCustomization", (handler, view) =>
            {
    #if ANDROID
                
                var map = handler.PlatformView as Android.Gms.Maps.GoogleMap;
                map.SetMapStyle(new Android.Gms.Maps.Model.MapStyleOptions(styleFile));
    #endif
            });
        }
    

    To use Map in Maui, you may refer to .NET MAUI Map.

    Hope it helps!