I use Xamarin.Forms.Maps and show my position and positions cars in range. I send request to database for take information about coordinates every 5 seconds. How I can show pins on Map and after 5 seconds refresh this pins with new coordinates in Map? My code here, but it isn`t work.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Threading;
using System.Threading.Tasks;
using Xamarin.Forms;
using Xamarin.Forms.Maps;
namespace CustomRenderer
{
public partial class MapPage : ContentPage
{
private System.Timers.Timer aTimer;
public MapPage()
{
InitializeComponent();
SetTimer();
}
public void RotateCars()
{
customMap.CustomPins = new List<CustomPin>();
double latitudeDoublecar15;
double longitudeDoublecar15;
var message = new Database();
CustomPin pin;
int timestamp = 0;//this timestamo is for cars moving simulation.
int tmpID15 = 10;//this is temp ID of the car
message.GetCarsApplyPeriodically(Convert.ToString(latitudeDoublecar15), Convert.ToString(longitudeDoublecar15), tmpID15, timestamp);
foreach (var b in Database.car)
{
pin = new CustomPin
{
Label = b.model,
Position = new Position(Convert.ToDouble(b.Latitude, CultureInfo.InvariantCulture), Convert.ToDouble(b.Longitude, CultureInfo.InvariantCulture)),
Type = PinType.Place
};
customMap.Pins.Add(pin);
customMap.CustomPins.Add(pin);
}
if (timestamp < 11)
{
timestamp++;
}
else
{
timestamp = 0;
}
CustomPin myPin = new CustomPin
{
Type = PinType.Place,
Label = DataManager.carsInRange.Count.ToString(),
Position = new Position(latitudeDoublecar15, longitudeDoublecar15),
Address = "my"
};
customMap.Pins.Add(myPin);
customMap.CustomPins.Add(myPin);
customMap.MoveToRegion(MapSpan.FromCenterAndRadius(new Position(latitudeDoublecar15, longitudeDoublecar15), Distance.FromKilometers(0.9)));
Content = customMap;
Task.Delay(5000);
customMap.Pins.Clear();
customMap.CustomPins.Clear();
RotateCars();
}
}
private void SetTimer()
{
// Create a timer with a five second interval.
aTimer = new System.Timers.Timer(5000);
// Hook up the Elapsed event for the timer.
aTimer.Elapsed += OnTimedEvent;
aTimer.AutoReset = true;
aTimer.Enabled = true;
}
private void OnTimedEvent(Object source, ElapsedEventArgs e)
{
RotateCars();
}
And my method does not work
private void OnTimedEvent(Object source, ElapsedEventArgs e)
{
RotateCars();
}
In Xamarin it would be better to use Device.StartTimer .
Device.StartTimer(TimeSpan.FromSeconds(5),()=> {
RotateCars();
return true;
});