kadoshms / ionic2-autocomplete

Ionic 2 autocomplete component
MIT License
149 stars 108 forks source link

Google Places autocomplete #56

Closed lpeppe closed 7 years ago

lpeppe commented 7 years ago

Hi, I'm trying to use this component with google places API, but I can't figure out how to make it work properly. I saw the example in the documentation but I don't understand where to specify the json field to show in the autocomplete. In my case I have this json object:

https://developers.google.com/maps/documentation/javascript/reference#AutocompletePrediction

and I need to use the description field for the autocomplete. Any ideas?

kadoshms commented 7 years ago

Hey, You should implement a service extending the base AutoCompleteService, which by demand should fetch the data from google, and return the observeable/promise/plain array result back to the component. In your case, you can use the description field as your labelAttribute, and this will display the descriptions as your search result. You can also implement your own template, and display as much fields as you wish to (please refer to the docs).

Was I clear enough?

lpeppe commented 7 years ago

Thanks for your reply. My problems is that the method I'm using to get predictions (getPlacePredictions) has no return value:

https://developers.google.com/maps/documentation/javascript/reference#AutocompleteService

here's my code:

getResults(keyword: string) {
    var request = {
      input: keyword,
      componentRestrictions: { country: 'it' },
    };
    this.autocomplete.getPlacePredictions(request, (pred, status) => {
      //here I have data
    });
  }
kadoshms commented 7 years ago

You can wrap the fetch method with an Observeable, and return the observable:

It should look something like that (not accurate, this is just the idea):

getResults(keyword: string) {
    var request = {
      input: keyword,
      componentRestrictions: { country: 'it' },
    };
    return new Observeable(observer => {
           this.autocomplete.getPlacePredictions(request, (pred, status) => {
               observer.next(pred)l
          });
    });
  }

You can read more about observeables heres : https://angular-2-training-book.rangle.io/handout/observables/using_observables.html

lpeppe commented 7 years ago

Thank you so much, it works like a charm!