How to set a default value for a Google places API auto complete textbox

后端 未结 2 904
心在旅途
心在旅途 2021-02-14 18:41

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 work

2条回答
  •  野趣味
    野趣味 (楼主)
    2021-02-14 19:31

    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

提交回复
热议问题