Hi I am having trouble with linking autocmplete to read from google api, can you please help me out?
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Net.Http;
using System.Threading.Tasks;
using System.Xml.Linq;
using Xamarin.Forms;
namespace Giftoria.MobileV2.Views.ShoppingCart
{
public partial class CartDetailsPage : ContentPage
{
public CartDetailsPage ()
{
InitializeComponent();
autoComplete.DataSource = new GooglePlacesSuggestion(autoComplete.Text).PlacesCollection;
autoComplete.DisplayMemberPath = "Name";
}
public class Places
{
private int id;
public int ID
{
get { return id; }
set { id = value; }
}
private string name;
public string Name
{
get { return name; }
set { name = value; }
}
}
public class GooglePlacesSuggestion
{
private ObservableCollection<Places> placesCollection;
public ObservableCollection<Places> PlacesCollection
{
get { return placesCollection; }
set { placesCollection = value; }
}
public GooglePlacesSuggestion(string address )
{
var places = GetPlacesAutocompleteAsync(address).Result;
placesCollection = new ObservableCollection<Places>(places);
}
public async Task<List<Places>> GetPlacesAutocompleteAsync(string search)
{
// from: https://developers.google.com/places/documentation/autocomplete
// e.g. https://maps.googleapis.com/maps/api/place/autocomplete/xml?input=Kirk&key=AddYourOwnKeyHere
string request = string.Format("https://maps.googleapis.com/maps/api/place/autocomplete/xml?input={0}&key={1}", search, "");
var xml = await (new HttpClient()).GetStringAsync(request);
var results = XDocument.Parse(xml).Element("AutocompletionResponse").Elements("prediction");
var suggestions = new List<Places>();
foreach (var result in results)
{
var suggestion = result.Element("description").Value;
int.TryParse(result.Element("place_id").Value, out int placeId);
suggestions.Add(new Places() { ID=placeId, Name=suggestion });
}
return suggestions;
}
}
}
}