更新GPS地图标记位置Xamarin

本文关键字:位置 Xamarin 图标 GPS 地图 更新 | 更新日期: 2023-09-27 18:11:46

我试图根据我的位置更新启动时放置的标记的位置。然而,第一个标记是在应用程序打开但不更新时放置的。没有看到任何物理变化,"计时器被调用"正在写入控制台,所以我知道计时器正在工作。我的问题是:为什么它不通过计时器更新我的标记的位置?如果有更好的方法,我愿意接受建议。

下面是我的代码:

GoogleMap mMap;
LocationManager _locationManager;
Location _currentLocation;
String _locationProvider;
TextView addresstxt;
MarkerOptions options = new MarkerOptions();
public void OnMapReady(GoogleMap googleMap)// This works as it should on start up.
{
    mMap = googleMap;
    LatLng latlng = new LatLng(_currentLocation.Latitude, _currentLocation.Longitude);
    CameraUpdate camera = CameraUpdateFactory.NewLatLngZoom(latlng, 18);
    mMap.MoveCamera(camera);

    options.SetPosition(latlng);
    options.SetTitle("Vehicle");
    options.SetSnippet("Your vehicle is here.");
    options.Draggable(false);
    mMap.AddMarker(options);
}
private void CountDown()
{
    System.Timers.Timer timer = new System.Timers.Timer();
    timer.Interval = 1000;
    timer.Elapsed += OnTimedEvent;
    timer.Enabled = true;

}
private void OnTimedEvent(object sender, System.Timers.ElapsedEventArgs e)
{
    Console.WriteLine("Timer called");
    mMap.Clear();
    LatLng latlng = new LatLng(_currentLocation.Latitude, _currentLocation.Longitude);
    CameraUpdate camera = CameraUpdateFactory.NewLatLngZoom(latlng, 18);
    mMap.MoveCamera(camera);
    MarkerOptions options = new MarkerOptions()
        .SetPosition(latlng)
        .SetTitle("Vehicle")
        .SetSnippet("Your vehicle is here.")
        .Draggable(false);
    mMap.AddMarker(options);
}

更新GPS地图标记位置Xamarin

我猜这可能是因为你永远不知道定时器回调在哪个线程上运行,通常UI更新需要在UI线程上完成。尝试用RunOnUiThread()运行代码来更新UI线程上的标记,例如:

RunOnUiThread(() => 
{
    mMap.Clear();
    LatLng latlng = new LatLng(_currentLocation.Latitude, _currentLocation.Longitude);
    CameraUpdate camera = CameraUpdateFactory.NewLatLngZoom(latlng, 18);
    mMap.MoveCamera(camera);
    MarkerOptions options = new MarkerOptions()
        .SetPosition(latlng)
        .SetTitle("Vehicle")
        .SetSnippet("Your vehicle is here.")
        .Draggable(false);
    mMap.AddMarker(options);
});