【发布时间】:2021-01-03 20:21:32
【问题描述】:
我已成功将 Google 地图实施到我的 Xamarin Forms 项目中,但现在我想更改其样式。我想使用a style from SnazzyMaps,但我不知道该怎么做。我在论坛上读到您可以将 SnazzyMaps 中的 json 加载到应用程序中,但我不知道该怎么做。
【问题讨论】:
标签: google-maps xamarin xamarin.forms
我已成功将 Google 地图实施到我的 Xamarin Forms 项目中,但现在我想更改其样式。我想使用a style from SnazzyMaps,但我不知道该怎么做。我在论坛上读到您可以将 SnazzyMaps 中的 json 加载到应用程序中,但我不知道该怎么做。
【问题讨论】:
标签: google-maps xamarin xamarin.forms
在您自定义的Xamarin.Forms GoogleMap 渲染器中,您可以使用 json 内容设置样式:
Xamarin.Android 示例:
googleMap.SetMapStyle(MapStyleOptions.LoadRawResourceStyle(this, Resource.Raw.map_style_night));
Xamarin.iOS 示例:
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
注意:使用当前 Xamarin.Google.iOS.Maps 绑定 (v2.1.0.2 ) 因为这将导致硬崩溃 (SIGSEGV)。我必须创建一个自定义绑定以允许 NSError 作为 out var 以确定是否正确解析了 json(也需要 Google iOS Map v2.4.30121.0 中的最新修复,因为 Xamarin 正在绑定/捆绑较旧的 @987654333 @版本)。
【讨论】:
SetMapStyle 是 native Android GoogleMap 类的方法,您需要在自定义渲染器中使用它。
Android.Gms.Maps.GoogleMap.SetMapStyle(在Xamarin.GooglePlayServices.Maps 包中)
Xaml:
<StackLayout VerticalOptions="FillAndExpand" Padding="1,10,0,0">
<maps:Map
x:Name="MyMap"
IsShowingUser="true"/>
</StackLayout>
我从后面的代码中调用它:
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);
不要忘记将 .json 作为嵌入式资源。
【讨论】: