amay077 / Xamarin.Forms.GoogleMaps

Map library for Xamarin.Forms using Google maps API
https://www.nuget.org/packages/Xamarin.Forms.GoogleMaps/
MIT License
544 stars 344 forks source link

MoveToRegion using timer #600

Open BullT opened 5 years ago

BullT commented 5 years ago

Hi,

I want update map position every 5000ms using MoveToRegion. If I use MoveToRegion without timer event, it work. The problem is when I want use MoveToRegion in a timer event.

How can I refresh my current position every 5000ms?

Thanks,

This is my code:

    #region Constructor
    public MapViewModel()
    {
        System.Timers.Timer aTimer = new System.Timers.Timer(5000);
        aTimer.Elapsed += OnTimedEvent;
        aTimer.AutoReset = true;
        aTimer.Enabled = true;
    }
    #endregion

    #region Methods
    private async void OnTimedEvent(object sender, ElapsedEventArgs e)
    {
        var location = await Geolocation.GetLocationAsync();
        var position = new Position(location.Latitude, location.Longitude);
        this.myMap.MoveToRegion(MapSpan.FromCenterAndRadius(position, Distance.FromKilometers(0.25)));
    }
    #endregion
Sonnenspeer commented 5 years ago

What is the exact problem?

Probably it's because the timer execution is not on the same thread as the map. Try to wrap around "Device.BeginInvokeOnMainThread()" to call it safely on the main thread.

BullT commented 5 years ago

Hi Sonnespeer,

First of all, thanks for your answer. You are right, I haven't explained the problem.

The problem is: When the Timer rise the event to move the map to user position, the map doesn't move.

This afternoon I'll try your proposal and inform you about results (If you have a better approach to solve it, please let me know).

Thanks, BullT

BullT commented 5 years ago

Hi Sonnespeer,

I tried it and works.

This is the code (if you think that there is a better solution, please let me know), thanks.

#region Constructor
public MapViewModel()
{
    System.Timers.Timer aTimer = new System.Timers.Timer(5000);
    aTimer.Elapsed += OnTimedEvent;
    aTimer.AutoReset = true;
    aTimer.Enabled = true;
}
#endregion

#region Methods
private void OnTimedEvent(object sender, ElapsedEventArgs e)
{
    var location = await Geolocation.GetLocationAsync();
    var position = new Position(location.Latitude, location.Longitude);

    Device.BeginInvokeOnMainThread(() =>
    {
        this.myMap.MoveToRegion(MapSpan.FromCenterAndRadius(position, Distance.FromKilometers(0.25)));
    });
}
#endregion