Encountering an error in the autocomplete feature for Angular Maps (AGM), which reads:
ERROR Error: Uncaught (in promise): TypeError: Cannot read property 'nativeElement' of undefined
TypeError: Cannot read property 'nativeElement' of undefined
This issue arises when utilizing ElementRef
within Angular, particularly with
public searchElement: ElementRef;
.
The error occurs at this line:
public latitude: number;
public longitude: number;
public searchControl: FormControl;
public zoom: number;
@ViewChild("search")
public searchElementRef: ElementRef;
constructor(
private mapsAPILoader: MapsAPILoader,
private ngZone: NgZone
) {}
ngOnInit() {
// Setting default values for Google Maps
this.zoom = 4;
this.latitude = 39.8282;
this.longitude = -98.5795;
// Creating a search FormControl
this.searchControl = new FormControl();
// Setting current position
this.setCurrentPosition();
// Loading Places Autocomplete
this.mapsAPILoader.load().then(() => {
let autocomplete = new google.maps.places.Autocomplete(this.searchElementRef.nativeElement, {
types: ["address"]
});
autocomplete.addListener("place_changed", () => {
this.ngZone.run(() => {
// Retrieving the place result
let place: google.maps.places.PlaceResult = autocomplete.getPlace();
// Verifying the result
if (place.geometry === undefined || place.geometry === null) {
return;
}
// Setting latitude, longitude, and zoom
this.latitude = place.geometry.location.lat();
this.longitude = place.geometry.location.lng();
this.zoom = 12;
});
});
});
}
In my view component
<div class="form-group">
<input placeholder="search for location" autocorrect="off" autocapitalize="off" spellcheck="off" type="text" class="form-control" #search [formControl]="searchControl">
</div>
<agm-map [latitude]="latitude" [longitude]="longitude" [scrollwheel]="false" [zoom]="zoom">
<agm-marker [latitude]="latitude" [longitude]="longitude"></agm-marker>
</agm-map>
I am using this setup in two components; it functions correctly in one but throws the aforementioned error in the other. I have attempted to use different names for the element reference without success.