0

我很新的Xamarin,所以請沒有恨......Xamarin的Android谷歌地圖更新地圖標記異步

我想創建一個谷歌地圖應用程序,它顯示了所有當前飛行的飛行員VATSIM(VATSIM是一個在線網絡飛行simers)。

我在地圖上顯示帶有標記的飛行員(帶有自定義圖像)。

目前我只在啓動時更新地圖一次!

private void drawPilots() 
{ 
    List<VatsimPilot> pilots = Parser.GetPilots(); 

    var matrix = new Matrix(); 

    foreach (var pilot in pilots) 
    { 
     matrix.PostRotate(float.Parse(pilot.Heading.ToString())); 

     _map.AddMarker(new MarkerOptions() 
      .SetPosition(new LatLng(pilot.Latitude, pilot.Longitude)) 
      .SetTitle(pilot.Callsign) 
      .SetIcon(BitmapDescriptorFactory.FromBitmap(
       Bitmap.CreateBitmap(_planeImg, 0, 0, _planeImg.Width, _planeImg.Height, matrix, true)))); 
    } 
} 

這工作正常。每個人都在正確的地方...

現在我想每x秒更新一次地圖。

我想出了這個代碼:

private void drawPilots() 
{ 
    List<VatsimPilot> pilots; 
    Task.Factory.StartNew(() => 
    { 
     System.Diagnostics.Debug.WriteLine("Thread Started"); 
     while (true) 
     { 
      System.Diagnostics.Debug.WriteLine("Getting data"); 
      pilots = Parser.GetPilots(); 
      var matrix = new Matrix(); 

      RunOnUiThread(() => 
      { 
       _map.Clear(); 
       System.Diagnostics.Debug.WriteLine("Updating Map"); 
       foreach (var pilot in pilots) 
       { 
        matrix.PostRotate(float.Parse(pilot.Heading.ToString())); 

        _map.AddMarker(new MarkerOptions() 
         .SetPosition(new LatLng(pilot.Latitude, pilot.Longitude)) 
         .SetTitle(pilot.Callsign) 
         .SetIcon(BitmapDescriptorFactory.FromBitmap(
          Bitmap.CreateBitmap(_planeImg, 0, 0, _planeImg.Width, _planeImg.Height, matrix, true)))); 
       } 
      }); 

      Thread.Sleep(Constants.UPDATE_INTERVALL_TIME); 
     } 
    }); 
} 

有了這個代碼,我沒有看到地圖上的任何標記,但是地圖是非常非常laggy,幾秒鐘後,應用程序崩潰。 Visual Studio中的輸出窗口不是很有用,因爲它不斷顯示有關工作人員的信息。 Intervall時間目前設置爲10秒。

感謝您的幫助提前!

+0

可否請你分享一個基本的演示或更完整重現這個問題? –

+0

我想我需要查看一些代碼來幫助您確定問題並請包含完整的診斷錯誤日誌。 –

回答

0

地圖非常非常滯後,幾秒鐘後應用程序崩潰。

我認爲東西會阻止你的UI線程並導致應用程序崩潰。當Android應用程序的UI線程被阻塞太久時,會觸發"Application Not Responding" (ANR)錯誤。

我想每x秒更新一次地圖。

您可以創建一個任務,它可以幫助你更新Map每x秒:

void ChangedMapData() 
{ 
    Task.Delay(x000).ContinueWith(t => 
    { 
     UpdateYourMap(); 
     ChangedMapData();//This is for repeate every xs. 
    }, TaskScheduler.FromCurrentSynchronizationContext()); 
} 
+0

@Maxlisui,你解決了你的問題嗎? –