Google Place Api Prediction类强制转换为Position或类似值

问题描述 投票:0回答:1

我正在研究Xamarin Forms项目。我有一个非常简单的页面,求职者在其中输入位置(例如纽约)和半径(picker)来搜索职位。我的PageViewModel中有以下代码:

public class SearchPageViewModel : BaseViewModel

    {

        private readonly INavigation _navigation;

        private readonly GooglePlacesApiService _api;

        private IEnumerable<JobPost> Posts;
        public int RadiusIndex {get;set;}

        public SearchPageViewModel (INavigation navigation, IEnumerable<JobPost> posts)

        {

            _navigation = navigation;
            var settings = GoogleApiSettings.Builder.WithApiKey("MY_API_KEY").Build();
            _api = new GooglePlacesApiService(settings);
            this.posts =posts;

        }

        public ICommand DoSearchCommand

        => new Command(async () => await DoSearchAsync().ConfigureAwait(false), () => CanSearch);

        public ICommand SelectItemCommand

        => new Command<Prediction>(async (prediction) =>

        {

             //!!!Filter jobposts based on position and radius to be able to display it!!!

            _api.ResetSessionToken();

        });

        private string _searchText;

        public string SearchText
        {

            get => _searchText;

            set 
            {
                if (SetProperty(ref _searchText, value))

                    OnPropertyChanged("CanSearch");
            }

        }

        private List<Prediction> _results;

        public List<Prediction> Results

        {

            get => _results;

            set => SetProperty(ref _results, value);

        }



        public bool CanSearch => !string.IsNullOrWhiteSpace(SearchText) && SearchText.Length > 2;

        private async Task DoSearchAsync()

        {

            var results = await _api.GetPredictionsAsync(SearchText)

                                    .ConfigureAwait(false);

            if(results != null && results.Status.Equals("OK"))

            {

                ResultCount = results.Items.Count;

                Results = results.Items;

                OnPropertyChanged("HasResults");

            }

        }

    }

public class JobPost
{
    public Position Location {get;set;}
}

确定,到目前为止效果很好。单击搜索按钮后,求职者将获得预测列表并选择一个位置。但是现在的问题是,如何获取所选择的预测的位置(经度和纬度),因此我可以筛选职位,以便将结果显示给求职者。预先感谢。

xamarin xamarin.forms google-places-api
1个回答
0
投票

使用Essentials GeoCoding插件

var address =  "New York";
var locations = await Geocoding.GetLocationsAsync(address);

[locations将是潜在匹配项的列表,每个都有纬度/经度

var location = locations?.FirstOrDefault();
if (location != null)
{
    Console.WriteLine($"Latitude: {location.Latitude}, Longitude: {location.Longitude}, Altitude: {location.Altitude}");
}
© www.soinside.com 2019 - 2024. All rights reserved.