Xamarin Forms Maps - 如何获取 Zoom 的值并在其上添加侦听器?

Emi*_*m23 1 maps zooming xamarin.forms

我认为一切都在标题中,我正在使用 PCL 逻辑

预先感谢 !

Emi*_*m23 6

然后我找到了解决方案!

你有你的地图,它继承自 Xamarin 地图控件:

public class CustomMap : Map
{
    // Your others properties

    public static readonly BindableProperty ZoomLevelProperty =
        BindableProperty.Create(nameof(ZoomLevel), typeof(Distance), typeof(CustomMap), new Distance());
    public Distance ZoomLevel
    {
        get { return (Distance)GetValue(ZoomLevelProperty); }
        set { SetValue(ZoomLevelProperty, value); }
    }

    #region Constructor
    public CustomMap()
    {
        this.PropertyChanged += (object sender, PropertyChangedEventArgs e) =>
        {
            CustomMap map = sender as CustomMap;
            if (map.VisibleRegion != null)
            {
                this.ZoomLevel = map.VisibleRegion.Radius;
                Debug.WriteLine("Xamarin Forms Map Radius: {0} Kilometers | {1} Meters | {2} Miles.", ZoomLevel.Kilometers, ZoomLevel.Meters, ZoomLevel.Miles);
            }
        };
    }
    #endregion
}
Run Code Online (Sandbox Code Playgroud)

让我解释:

因此,一旦定义了CustomMap,就必须像我一样添加 Zoom 属性。这个属性必须是一个Distance类型。现在,如何设置?在构造函数中,例如,你可以像我一样做。对于地图上的每个手势,将设置您的缩放属性,然后您可以使用km、meters 和 miles 进行操作

注意:但是,它似乎没有ZoomLevel在构造函数中设置,它似乎至少需要一个手势,但我正在研究它,稍后我会编辑我的答案!

如果您需要在每次设置缩放时在渲染器中编辑某些内容,您可以执行以下操作:(UWP 示例,但对于其他 Android/iOS 来说有点相同)

[assembly: ExportRenderer(typeof(CustomMap), typeof(CustomMapRenderer))]
namespace Project.UWP.CustomRenderer
{
    public class CustomMapRenderer : MapRenderer
    {
        MapControl nativeMap;
        CustomMap customMap;

        protected override void OnElementChanged(ElementChangedEventArgs<Map> e)
        {
            base.OnElementChanged(e);

            if (e.NewElement != null)
            {
                customMap = (CustomMap)e.NewElement;
                nativeMap = Control as MapControl;
            }
        }

        protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            base.OnElementPropertyChanged(sender, e);

            if (this.Element == null || this.Control == null)
                return;

            //From here, each time the zoom is set you going into the if()
            if (e.PropertyName == CustomMap.ZoomLevelProperty.PropertyName)
                ZoomSetted();
        }

        private void ZoomSetted()
        {
            if (customMap != null && nativeMap != null)
            {
                Debug.WriteLine("Hello World ! You can access the zoom like that =>"); 
                Debug.WriteLine("Xamarin Forms Map Radius: {0} Kilometers | {1} Meters | {2} Miles.", 
                    customMap.ZoomLevel.Kilometers, 
                    customMap.ZoomLevel.Meters, 
                    customMap.ZoomLevel.Miles);
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)