Radu
Radu

Reputation: 646

Use custom map style in Xamarin Forms?

I have successfully implemented Google Maps into my Xamarin Forms project but now I want to change its style. I want to use a style from SnazzyMaps but I don't know how to do that. I have read on the forums that you can load the json from SnazzyMaps into the application but I have no idea how to do that.

Upvotes: 5

Views: 2252

Answers (2)

KalleP
KalleP

Reputation: 329

Xaml:

     <StackLayout VerticalOptions="FillAndExpand" Padding="1,10,0,0">
            <maps:Map        
                x:Name="MyMap" 
                IsShowingUser="true"/>
        </StackLayout>

I call this from code behind:

var assembly = typeof(MapPage).GetTypeInfo().Assembly;
            Stream stream = assembly.GetManifestResourceStream("MyApp.Helpers.Style.json");
            string Json = "";
            using (var reader = new StreamReader(stream))
            {
                Json = reader.ReadToEnd();
            }
            MyMap.MapStyle = MapStyle.FromJson(Json);

Dont forget to put the .json as Embedded Resource.

Upvotes: 0

SushiHangover
SushiHangover

Reputation: 74209

In your custom Xamarin.Forms GoogleMap renderer, you can set the style with the json content:

Xamarin.Android Example:

googleMap.SetMapStyle(MapStyleOptions.LoadRawResourceStyle(this, Resource.Raw.map_style_night));

Xamarin.iOS Example:

googleMapView.MapType = MapViewType.Normal; // Must be normal
var styleResource = NSBundle.MainBundle.GetUrlForResource("map_style_night", "json");
googleMapView.MapStyle = MapStyle.FromUrl(styleResource, null); // DO NOT pass an NSError, hard-crash / SIGSEGV

Note: Do not pass an NSError instance to MapStyle.FromUrl or MapStyle.FromJson with the current Xamarin.Google.iOS.Maps binding (v2.1.0.2) as this will cause a hard-crash (SIGSEGV). I had to create a custom binding to allow NSError as an out var in order to determine if the json is parsed correctly (also needed to the latest fixes in Google iOS Map v2.4.30121.0 as Xamarin is binding/bundling the older 2.1.0.2 version).

enter image description here

Upvotes: 9

Related Questions