这是一个很长的内容,但这里有……显然,您希望将服务调用代码放在服务class 中,并将所有其他代码放在ViewModel 中。您可能还希望在服务调用方法中或周围添加更多的 null 和错误检查。
我忽略的一个重要部分是 Google 要求在执行搜索时显示 Google 徽标。所以下载their icon 并将其添加到用户界面。我只在用户关注Entry 时显示它。
这些是 Places 模型和我自己的 Address 模型:
public class AddressInfo {
public string Address { get; set; }
public string City { get; set; }
public string State { get; set; }
public string ZipCode { get; set; }
public double Longitude { get; set; }
public double Latitude { get; set; }
}
public class PlacesMatchedSubstring {
[Newtonsoft.Json.JsonProperty("length")]
public int Length { get; set; }
[Newtonsoft.Json.JsonProperty("offset")]
public int Offset { get; set; }
}
public class PlacesTerm {
[Newtonsoft.Json.JsonProperty("offset")]
public int Offset { get; set; }
[Newtonsoft.Json.JsonProperty("value")]
public string Value { get; set; }
}
public class Prediction {
[Newtonsoft.Json.JsonProperty("id")]
public string Id { get; set; }
[Newtonsoft.Json.JsonProperty("description")]
public string Description { get; set; }
[Newtonsoft.Json.JsonProperty("matched_substrings")]
public List<PlacesMatchedSubstring> MatchedSubstrings { get; set; }
[Newtonsoft.Json.JsonProperty("place_id")]
public string PlaceId { get; set; }
[Newtonsoft.Json.JsonProperty("reference")]
public string Reference { get; set; }
[Newtonsoft.Json.JsonProperty("terms")]
public List<PlacesTerm> Terms { get; set; }
[Newtonsoft.Json.JsonProperty("types")]
public List<string> Types { get; set; }
}
public class PlacesLocationPredictions {
[Newtonsoft.Json.JsonProperty("predictions")]
public List<Prediction> Predictions { get; set; }
[Newtonsoft.Json.JsonProperty("status")]
public string Status { get; set; }
}
这里我们调用 Places API:
public const string GooglePlacesApiAutoCompletePath = "https://maps.googleapis.com/maps/api/place/autocomplete/json?key={0}&input={1}&components=country:us"; //Adding country:us limits results to us
public const string GooglePlacesApiKey = "bTafrOPmO4LpPgAl34r5wQ6LFRWhgTxBW80-3GK";
private static HttpClient _httpClientInstance;
public static HttpClient HttpClientInstance => _httpClientInstance ?? (_httpClientInstance = new HttpClient());
private ObservableCollection<AddressInfo> _addresses;
public ObservableCollection<AddressInfo> Addresses {
get => _addresses ?? (_addresses = new ObservableCollection<AddressInfo>());
set {
if(_addresses != value) {
_addresses = value;
OnPropertyChanged();
}
};
}
private string _addressText;
public string AddressText {
get => _addressText;
set {
if(_addressText != value) {
_addressText = value;
OnPropertyChanged();
}
};
}
public async Task GetPlacesPredictionsAsync() {
// TODO: Add throttle logic, Google begins denying requests if too many are made in a short amount of time
CancellationToken cancellationToken = new CancellationTokenSource(TimeSpan.FromMinutes(2)).Token;
using(HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, string.Format(GooglePlacesApiAutoCompletePath, ConstantKeys.GooglePlacesApiKey, WebUtility.UrlEncode(_addressText)))) { //Be sure to UrlEncode the search term they enter
using(HttpResponseMessage message = await HttpClientInstance.SendAsync(request, HttpCompletionOption.ResponseContentRead, cancellationToken).ConfigureAwait(false)) {
if(message.IsSuccessStatusCode) {
string json = await message.Content.ReadAsStringAsync().ConfigureAwait(false);
PlacesLocationPredictions predictionList = await Task.Run(() => JsonConvert.DeserializeObject<PlacesLocationPredictions>(json)).ConfigureAwait(false);
if(predictionList.Status == "OK") {
Addresses.Clear();
if(predictionList.Predictions.Count > 0) {
foreach(Prediction prediction in predictionList.Predictions) {
Addresses.Add(new AddressInfo {
Address = prediction.Description
});
}
}
} else {
throw new Exception(predictionList.Status);
}
}
}
}
}
现在是 UI...
<Entry Text="{Binding AddressText}"
TextChanged="OnTextChanged" />
<ListView ItemsSource="{Binding Addresses}">
<ListView.ItemTemplate>
<DataTemplate>
<TextCell Text="{Binding Address}"/>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
以及后面的代码:
private async void OnTextChanged(object sender, EventArgs eventArgs) {
if(!string.IsNullOrWhiteSpace(ViewModel.AddressText)) {
await ViewModel.GetPlacesPredictionsAsync();
}
}