GetLocation(address: string) {
var geocoder = new google.maps.Geocoder();
geocoder.geocode({ 'address': address }, (results, status) => {
if (status == google.maps.GeocoderStatus.OK) {
this.lat = results[0].geometry.location.lat();
this.lng = results[0].geometry.location.lng(); <== this.lat value is undefined
}
else {
alert("Something went wrong : " + status);
}
});
}
Here I cannot assign value of component level variable 'lat' and 'lng' inside the geocode function. FYI: there are values in location object of result inside it, but after assigning the value it is still undefined I don't know why?
import { Component, OnInit, NgZone } from '@angular/core'; <= 1. I have to import NgZone
constructor(private ngZone: NgZone) { } <= 2. declared it here
ngOnInit() { }
GetLocation(address: string) {
var geocoder = new google.maps.Geocoder();
geocoder.geocode({ 'address': address }, (results, status) => this.ngZone.run(() => { <= 3. and used it here
if (status == google.maps.GeocoderStatus.OK) {
this.lat = results[0].geometry.location.lat();
this.lng = results[0].geometry.location.lng();
}
else {
alert("Something went wrong : " + status);
}
}));
}
I found the solution for this. I have to import NgZone from '@angular/core' and used this.ngZone.run() function inside call back function as in 3. hint.