Skip to content Skip to sidebar Skip to footer

How To Set A Default Value For A Google Places Api Auto Complete Textbox

I'm working on a page close enough to the one in google samples https://developers.google.com/maps/documentation/javascript/examples/places-autocomplete-addressform and it works fi

Solution 1:

I had the same requirement of setting the initial location when the Map initally loads.

This is how I did it:

As Jon Hannah mentioned, I used the Autocomplete Service to get the prediction, then used the first prediction to get the Place (using place_id). Populated the Autocompelete input with my default location string. Finally triggered the place_change event.

this.input.nativeElement.value = this.testLocationStr;

  let autocompleteService = new google.maps.places.AutocompleteService();
  let request = {input: this.testLocationStr};
  autocompleteService.getPlacePredictions(request, (predictionsArr, placesServiceStatus) => {
    console.log('getting place predictions :: predictionsArr = ', predictionsArr, '\n',
      'placesServiceStatus = ', placesServiceStatus);

    let placeRequest = {placeId: predictionsArr[0].place_id};
    let placeService = new google.maps.places.PlacesService(this.mapObj);
    placeService.getDetails(placeRequest, (placeResult, placeServiceStatus) => {
      console.log('placeService :: placeResult = ', placeResult, '\n',
        'placeServiceStatus = ', placeServiceStatus);

      this._handlePlaceChange(placeResult);

    });
  });

Plunker: https://plnkr.co/edit/9oN6Kg?p=preview

Solution 2:

I came across this post while trying to solve for a similar use case (populating the Autocomplete with the last place a user searched for).

As far as I can tell it is not possible to set a default for the Autocomplete that it recognises as a place. However, I think you can simulate this effect using the Autocomplete Service (example - also see the reference sections on #AutocompletePrediction and #PlacesService):

  • Set your Autocomplete to the identified city and country as you are already
  • Pass the city and country to the Autocomplete Service
  • Determine the place ID of your preferred prediction (e.g. select the first prediction with type = 'city')
  • Use the Places Service to get the details (PlaceResult) for your chosen place ID (same result as using autocomplete.getPlace())
  • Have a callback that does what you need with the PlaceResult

This gives your user the impression that the Autocomplete is in use. If the result is what they need, great! If they want to search for a different place set up your autocomplete to listen for place_changed and run autocomplete.getPlace() followed by the same callback.

Post a Comment for "How To Set A Default Value For A Google Places Api Auto Complete Textbox"