angulartypescriptgoogle-apigoogle-placesgoogle-places-autocomplete

Load Google places api into component library (no index.html file)


Currently in my code "places" is undefined. This is in a component library that is consumed by other applications so it it's self does not have access to an Index.html file.

.ts code

 import { MapsAPILoader } from '@agm/core';
 import { Component, ElementRef, Inject, NgZone, OnInit, ViewChild } from '@angular/core';
 import { FormControl } from '@angular/forms';
 import {} from 'googlemaps';
 @Component({
   selector: 'lib-google-search',
   templateUrl: './google-search.component.html',
   styleUrls: ['./google-search.component.scss']
 })
 export class GoogleSearchComponent implements OnInit {
     zoom: number = 0;
     searchElementRef: ElementRef;
     searchControl:FormControl;
     latLong:any;
     google:any;
     @ViewChild('search',{static:false}) Component
      constructor(
      private mapsAPILoader: MapsAPILoader,
      private ngZone: NgZone,
      private elementRef:ElementRef
    ) { }  
    ngOnInit() {
    this.searchControl = new FormControl();
    this.mapsAPILoader.load().then(() => {
     const autoComplete = new google.maps.places.Autocomplete(this.searchElementRef.nativeElement, {
     types: [],
     componentRestrictions: {'country': 'USA'}
    });
    autoComplete.addListener('place_changed', () => {
    this.ngZone.run(() => {
      const place: google.maps.places.PlaceResult = autoComplete.getPlace();
      if (place.geometry === undefined || place.geometry === null){
        return;
      }
      const latlong = {
        latitude: place.geometry.location.lat,
        longitude : place.geometry.location.lng

      }
      this.latLong.push(latlong);
      this.searchControl.reset();
  });
 })
});
}  
}

I need some way of loading the places library without using the index.html file

Any help is greatly appreciated!


Solution

  • I ended up using Angular Google Maps (AGM) to load this library and it works well.

    import { AgmCoreModule } from '@agm/core';
    AgmCoreModule.forRoot({
      libraries:['places'],
      apiKey: 'your googleapi key'
    }),
    

    you can get this library here. https://angular-maps.com/