How to have Google Places search bar working with Ionic 4 / Angular 8 and agm-core?

2.8k Views Asked by At

I am using agm-core component to have Google maps in my app. Maps are showing fine. in my app.module.ts, I have the following:

AgmCoreModule.forRoot({
apiKey: '', // API key is defined here.
libraries: ['places', 'drawing', 'geometry']  }) 

In my html I have:

<ion-header></ion-header>
<ion-toolbar>

</ion-toolbar>
<div class="form-group">
<label>Enter address</label>
<input type="text" class="form-control
(keydown.enter)="$event.preventDefault()" placeholder="Search Nearest
Location" autocorrect="off" autocapitalize="off" spellcheck="off"
type="text" #search>
</div>
<agm-map 
[latitude]="latitude" 
[longitude]="longitude" 
[zoom]="zoom" >
 <agm-marker 
[latitude]="latitude" 
 [longitude]="longitude"></agm-marker>
</agm-map>
<h5>Address: {{address}}</h5>
<div>Latitude: {{latitude}}</div>
<div>Longitude: {{longitude}}</div>

and my ts file is:

    export class SiteDetailsComponent  implements OnInit {
  title = 'AGM project';
  latitude: number;
  longitude: number;
  zoom: number;

  address: string;
  private geoCoder;

  @ViewChild('search', { static: true })
  public searchElementRef: ElementRef;
constructor(

    private router: Router,
    private mapsAPILoader: MapsAPILoader,
    private ngZone: NgZone

  ) {}
ngOnInit() {
    // load Places Autocomplete
    this.mapsAPILoader.load().then(() => {
      this.setCurrentLocation();
      this.geoCoder = new google.maps.Geocoder();

      const autocomplete = new google.maps.places.Autocomplete(this.searchElementRef.nativeElement, {
        types: ['address']
      });

      autocomplete.addListener('place_changed', () => {
        this.ngZone.run(() => {
          // get the place result
          const place: google.maps.places.PlaceResult = autocomplete.getPlace();

          // verify result
          if (place.geometry === undefined || place.geometry === null) {
            return;
          }

          // set latitude, longitude and zoom
          this.latitude = place.geometry.location.lat();
          this.longitude = place.geometry.location.lng();
          this.zoom = 12;
        });
      });
    });
  }
  // Get Current Location Coordinates
  private setCurrentLocation() {
    if ('geolocation' in navigator) {
      navigator.geolocation.getCurrentPosition((position) => {
        this.latitude = position.coords.latitude;
        this.longitude = position.coords.longitude;
        this.zoom = 8;
        this.getAddress(this.latitude, this.longitude);
      });
    }
  }

  getAddress(latitude, longitude) {
    this.geoCoder.geocode({ location: { lat: latitude, lng: longitude } }, (results, status) => {
      if (status === 'OK') {
        if (results[0]) {
          this.zoom = 12;
          this.address = results[0].formatted_address;
        } else {
      }
      } else {
      }

    });
  }

The search bar does not pop down places at all. No errors are thrown. Maybe the problem comes from new version of @ViewChild come with angular 8. It is possible also that accessing DOM is different using Ionic 4 ?

Any idea to help me with this please?

Kind Regards

1

There are 1 best solutions below

0
On

I am not using agm-core component but I think the logic will be similar to what I have used to solve my issue. It is an angular 7 app using "ionic": "^5.4.4".

The html code is as shown below:

<ion-item>
  <ion-label class="ion-item-small" position="floating">Property Address</ion-label>
  <ion-input formControlName="autocomplete_input" id="autocomplete_input"
    autocomplete="off" (keyup)="keyUpHandler()">
  </ion-input>
</ion-item>

Then in order to handle the autocomplete this method is executed:

keyUpHandler(){
  if(this.your_form.get('autocomplete_input').value.length > 0)
{
  let inputfield = 
  document.getElementById('autocomplete_input').getElementsByTagName('input')[0];
  let autocomplete = new google.maps.places.Autocomplete((inputfield), {
    types: ['address'],
    componentRestrictions: {country: 'us'},
  });    
  //the below code has same behaviour as the working solution

  // autocomplete.addListener('place_changed', () => {
  //   this.zone.run(() => {
  //     const place = autocomplete.getPlace();
  //     console.log(place)
  //   });
  // });

  google.maps.event.addListener(autocomplete ,`place_changed`, () => {
    var place = autocomplete.getPlace();
    console.log(place)
 //your code goes here
  });
} 

This the only thing we have to do and we can access the google-api address in the following format:

Output Json