Xamarin Forms GetAddressesForPositionAsync

问题描述:

我想创建一个帮助器类来处理我的应用程序中的Geocoding和ReverseGeoCoding。Xamarin Forms GetAddressesForPositionAsync

我的挑战是下面这行代码实际上并没有等待调用的结果。

var possibleAddresses = await iobj_Geocoder.GetAddressesForPositionAsync(pobj_Position); 

在检索地址结果之前,控制返回到调用事件。任何帮助如何使这项工作将不胜感激。

帮助类代码:

using System.Linq; 
using Xamarin.Forms.Maps; 

namespace MapProblems 
{ 
    public class MapHelper 
    { 
     private Geocoder iobj_Geocoder; 
     public string Address { get; set; } 

     public MapHelper() 
     { 
      iobj_Geocoder = new Geocoder(); 
     } 

     public async void GeoCodeAddress(Position pobj_Position) 
     { 

      var possibleAddresses = await iobj_Geocoder.GetAddressesForPositionAsync(pobj_Position); 

      Address = possibleAddresses.ToList()[0]; 
     } 

    } 
} 

调用助手类C#文件主页:

using System; 
using System.Diagnostics; 
using Xamarin.Forms; 
using Xamarin.Forms.Maps; 
namespace MapProblems 
{ 
    public partial class MainPage : ContentPage 
    { 
     MapHelper iobj_MapHelper; 
     public MainPage() 
     { 
      InitializeComponent(); 
      iobj_MapHelper = new MapHelper(); 
      this.Appearing += MainPage_Appearing; 

     } 

     private async void MainPage_Appearing(object sender, EventArgs e) 
     { 
      Device.BeginInvokeOnMainThread(() => 
      { 
       iobj_MapHelper.GeoCodeAddress(new Position(38.9047, -077.0310)); 
      } 
      ); 

      Debug.WriteLine("Address: " + iobj_MapHelper.Address); 
     } 
    } 
} 

所以这个例子中的最终结果是Address是任何空字符串时的Debug.WriteLine代码执行。

任何援助将不胜感激。

因为您的GeoCodeAddress方法是异步无效的,所以您的代码无法知道它何时完成。尝试使它成为一个异步任务:

public async Task<string> GeoCodeAddress(Position pobj_Position) 
{ 
    var possibleAddresses = await iobj_Geocoder.GetAddressesForPositionAsync(pobj_Position); 
    return possibleAddresses.ToList()[0]; 
} 

然后就可以调用它像这样:

private async void MainPage_Appearing(object sender, EventArgs e) 
{ 
    var address = await iobj_MapHelper.GeoCodeAddress(new Position(38.9047, -077.0310)); 
    Debug.WriteLine("Address: " + address); 
} 

此外,还要确保你的try/catch在异步void的方法,在有例外会崩溃的应用程序,如果他们去处理。

+0

我已经尝试了你的建议,但它不起作用,但我会再试一次并让你知道。 –

+0

OK,确实有效,它引发了我提交给MS的缺陷。对于大家的知识,如果您在Windows Phone 8.1模拟器上运行上述代码,则会返回1个地址。如果您在Windows 10移动模拟器上运行它,则会返回零地址。我创建的应用程序是Windows Phone 8.1应用程序的FYI。 –