Привязки карт Google Xamarin: BindingPinsBehavior не показывает контакты на карте - PullRequest
0 голосов
/ 02 августа 2020

Я могу взаимодействовать с картой с помощью следующих функций. установка масштаба, текущего положения и даже отображение полигонов. Просто не могу отобразить какой-либо пин-код.

Я получаю данные пин-кода в MapView, и, как я тестировал, он виден в

Также добавлено событие щелчка на карте, которое может увидеть правильное количество контактов.

Проблема в том, что контакты не видны. Пробовали использовать PIN-код по умолчанию, а также настраиваемый PIN-код, используя .Icon

Это мой MapViewModel.cs

using MapApp.Mobile.Core.Contracts.Services.General;
using MapApp.Mobile.Core.ViewModels.Base;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using MapApp.Mobile.Core.Services.Data;
using MapApp.Mobile.Core.Contracts.Services.Data;
using System.Collections.ObjectModel;
using Xamarin.Forms.GoogleMaps;
using MapApp.Mobile.Core.Models;

using Xamarin.Forms.GoogleMaps.Bindings;
using Xamarin.Forms;


using Plugin.Geolocator.Abstractions;

namespace MapApp.Mobile.Core.ViewModels
{
    public class MapViewModel : ViewModelBase
    {
        private readonly IZoneService _zoneService;
        private readonly IAddressService _addressService;

        //Expands to a region
        private MapSpan _visibleRegion;
        public MapSpan VisibleRegion
        {
            get => _visibleRegion;
            set
            {
                _visibleRegion = value;
                RaisePropertyChanged(() => VisibleRegion);
            }
        }

        //Map collection of pins
        private ObservableCollection<Pin> _pins;
        public ObservableCollection<Pin> Pins
        {
            get => _pins;
            set
            {
                _pins = value;
                RaisePropertyChanged(() => Pins);
            }
        }

        private ObservableCollection<Polygon> _nogoZones;
        public ObservableCollection<Polygon> NogoZones
        {
            get => _nogoZones;
            set {
                _nogoZones = value;
                RaisePropertyChanged(() => NogoZones);
            }
        
        }

        public MoveToRegionRequest MoveToRegionRequest { get; } = new MoveToRegionRequest();

        public MapViewModel(IConnectionService connectionService,
            INavigationService navigationService, IDialogService dialogService,
            IZoneService zoneService, IAddressService addressService)
            : base(connectionService, navigationService, dialogService)
        {


            _zoneService = zoneService;
            _addressService = addressService;
        }

        public Command<MapClickedEventArgs> MapClickedCommand =>
            new Command<MapClickedEventArgs>(args =>
            {
                Pins.Add(new Pin
                {
                    Label = $"Pin{Pins.Count}",
                    Position = args.Point
                });
            });


        //public override async Task InitializeAsync(object navigationData)
        public override async Task InitializeAsync(object navigationData)
        {
            Coordinates defaultCoordinates = _zoneService.GetAssignedLatitudeLongitude();

            //Sets the visible view of the maps - 0.25 miles around the centre of the coord point
            VisibleRegion = MapSpan.FromCenterAndRadius(
                new Xamarin.Forms.GoogleMaps.Position(defaultCoordinates.Latitude, defaultCoordinates.Longitude),
                Distance.FromMiles(0.25));

            MoveToRegionRequest.MoveToRegion(VisibleRegion);


            //Get near by address to current location
            var addresses = await _addressService.GetNearbyAddressesAsync(defaultCoordinates.Latitude, defaultCoordinates.Longitude);

            //Now populate on the map                
            _pins = new ObservableCollection<Pin>();
            foreach (Models.Address a in addresses)
            {

                Xamarin.Forms.GoogleMaps.Pin p = new Xamarin.Forms.GoogleMaps.Pin();
                p.Type = PinType.Generic;
                p.Address = a.Address1;
                p.Label = a.AddressDisplay;
                p.Position = new Xamarin.Forms.GoogleMaps.Position((double)a.Latitude, (double)a.Longitude);
                p.Icon = BitmapDescriptorFactory.FromBundle(a.AddressStatus.Icon);


                _pins.Add(p);

            }
            Pins = new ObservableCollection<Pin>(_pins);
            RaisePropertyChanged(() => Pins);


            var zones = _zoneService.GetZones();

            foreach (var zone in zones)
            {
                Polygon zonePolygon = new Polygon
                {
                    StrokeColor = Color.DarkRed,
                    FillColor = Color.FromRgba(255, 0, 0, 0.5f),
                    StrokeWidth = 3f,
                    Tag = zone.Name,
                };
                foreach (var coordinates in zone.Bounds)
                {
                    zonePolygon.Positions.Add(new Xamarin.Forms.GoogleMaps.Position(coordinates.Latitude, coordinates.Longitude));
                }
                _nogoZones.Add(zonePolygon);
            }
        }

    }
}

И это MapView.xaml

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="MapApp.Mobile.Core.Views.MapView"
            xmlns:utility="clr-namespace:MapApp.Mobile.Core.Utility;assembly=MapApp.Mobile.Core"             
             utility:ViewModelLocator.AutoWireViewModel="True"             
             xmlns:maps="clr-namespace:Xamarin.Forms.GoogleMaps;assembly=Xamarin.Forms.GoogleMaps"
             xmlns:bindings="clr-namespace:Xamarin.Forms.GoogleMaps.Bindings;assembly=Xamarin.Forms.GoogleMaps.Bindings"
             Title="Map">
    
    <ContentPage.Content>
        <StackLayout>

            <Grid>
                <ListView VerticalOptions="FillAndExpand" Header="{Binding .}" Footer="{Binding .}" 
                  ItemsSource="{Binding Pins}" CachingStrategy="RecycleElement"
            SeparatorVisibility="Default"
            
            HasUnevenRows="True">
                    <ListView.HeaderTemplate>
                        <DataTemplate>
                            <Grid>
                                <Grid.RowDefinitions>
                                    <RowDefinition Height="8*"></RowDefinition>
                                    <RowDefinition Height="2*"></RowDefinition>
                                </Grid.RowDefinitions>
                                <Image HeightRequest="200" Grid.Row="0" Source="carousel3.jpg" Aspect="AspectFill"></Image>
                                <StackLayout Grid.Row="1">
                                    <Label Text="OUR SELECTION OF PIES" Style="{StaticResource PageHeaderStyle}" HorizontalOptions="CenterAndExpand"></Label>
                                </StackLayout>
                            </Grid>
                        </DataTemplate>
                    </ListView.HeaderTemplate>
                    <ListView.ItemTemplate>
                        <DataTemplate>
                            <ViewCell>
                                <Grid Margin="5" BackgroundColor="White" RowSpacing="2" HeightRequest="60">
                                    <Grid.RowDefinitions>
                                        <RowDefinition Height="*"></RowDefinition>
                                        <RowDefinition Height="*"></RowDefinition>
                                    </Grid.RowDefinitions>
                                    <Grid.ColumnDefinitions>
                                        <ColumnDefinition Width="50"></ColumnDefinition>
                                        <ColumnDefinition Width="*"></ColumnDefinition>
                                        <ColumnDefinition Width="60"></ColumnDefinition>
                                    </Grid.ColumnDefinitions>
                                    <!--<Image Grid.Row="0" Grid.RowSpan="2" HeightRequest="80" WidthRequest="100" VerticalOptions="Start" Margin="2,2,1,2" Source="{Binding ImageUrl}"></Image>-->
                                    <StackLayout Grid.Row="0" Grid.Column="1">
                                        <Label  Text="{Binding Address}" Margin="3" Style="{StaticResource PieTileNameStyle}" LineBreakMode="WordWrap"></Label>
                                    </StackLayout>
                                    <!--<Label Grid.Row="0" Grid.Column="2"  Margin="3" Text="{Binding Price, Converter={StaticResource LocalCurrencyConverter}}" Style="{StaticResource PieTilePriceStyle}" HorizontalTextAlignment="End"></Label>-->
                                    <StackLayout Grid.Column="1" Grid.Row="1">
                                        <Label  Margin="3" Grid.ColumnSpan="2" Text="{Binding Label}" Style="{StaticResource PieTileDescriptionStyle}"></Label>
                                    </StackLayout>
                                </Grid>
                            </ViewCell>
                        </DataTemplate>
                    </ListView.ItemTemplate>

                </ListView>
            </Grid>


            <maps:Map VerticalOptions="FillAndExpand"
                      MyLocationEnabled="True"
                      MapType="Hybrid">
                <maps:Map.Behaviors>
                    <bindings:BindingVisibleRegionBehavior Value="{Binding VisbleRegion}"/>
                    <bindings:MoveToRegionBehavior Request="{Binding MoveToRegionRequest}"/>
                    <bindings:BindingPolygonsBehavior Value="{Binding NogoZones}"/>
                    <bindings:BindingPinsBehavior Value="{Binding Pins}" />
                    <bindings:MapClickedToCommandBehavior Command="{Binding MapClickedCommand}"/>
                </maps:Map.Behaviors>

            </maps:Map>


        </StackLayout>
    </ContentPage.Content>
</ContentPage>

Очень признателен за любую помощь или предложения

1 Ответ

0 голосов
/ 20 августа 2020

Вам необходимо инициализировать ObservableCollection<Pin>, прежде чем вы сможете добавить к нему контакты. Создайте конструктор и инициализируйте ObservableCollection<Pin>, затем добавьте булавки в эту коллекцию.

...