jstuardo
jstuardo

Reputation: 4403

MAUI: How to move the map to the first item of ObservableCollection

I have this XAML page:

<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:vm="clr-namespace:TimeApp.ViewModels"
             x:Class="TimeApp.Views.UbicacionPage"
             xmlns:maps="clr-namespace:Microsoft.Maui.Controls.Maps;assembly=Microsoft.Maui.Controls.Maps"
             xmlns:sensors="clr-namespace:Microsoft.Maui.Devices.Sensors;assembly=Microsoft.Maui.Essentials"
             xmlns:model="clr-namespace:TimeApp.Models"
             x:DataType="vm:UbicacionViewModel">

    <maps:Map x:Name="TheMap" ItemsSource="{Binding Locations}">
        <x:Arguments>
            <MapSpan>
                <x:Arguments>
                    <sensors:Location Latitude="-33" Longitude="-70">
                    </sensors:Location>
                    <x:Double>0.01</x:Double>
                    <x:Double>0.01</x:Double>
                </x:Arguments>
            </MapSpan>
        </x:Arguments>
        <maps:Map.ItemTemplate>
            <DataTemplate x:DataType="model:LocationItem">
                <maps:Pin Address="{Binding Address}"
                          Label="{Binding Name}"
                          Location="{Binding Location}">
                </maps:Pin>
            </DataTemplate>
        </maps:Map.ItemTemplate>
    </maps:Map>
</ContentPage>

UbicacionViewModel is defined this way:

public partial class UbicacionViewModel : BaseViewModel
{
    public ObservableCollection<LocationItem> Locations { get; set; }

    public UbicacionViewModel()
    {
        Locations = new ObservableCollection<LocationItem>()
        {
            new LocationItem
            {
                Name = "My locatinon",
                Address = "My street",
                Location = new Location(-33, -70)
            }
        };
    }
}

When I run the application, the map points to the right point because I hardcoded the coordinates.

How can I get those coordinates dynamically where Latitude and Logitude comes from the first element in the collection?

Upvotes: 1

Views: 346

Answers (1)

Jason
Jason

Reputation: 89169

in the code behind

var pos = VM.Locations[0].Location;
var span = new MapSpan(pos,zoomx,zoomy);
TheMap.MoveToRegion(span);

because VisibleRegion is not bindable you can't do this directly from the VM or via binding

Upvotes: 2

Related Questions