Search code examples
angulargoogle-mapsnpmangular5google-geocoder

ngx-toastr not showing up on first click or Ui not updating in angular 5 Digest cycle using google map apis


I'm using ngx-toastr in my Angular 5 projects. I have user form through which I'm taking LAT and LNG for user reverse geocoding. This is the applied condition in my code.

If city not found then it should show toastr message but this toastr message does not show up on the first click when I pressed submit button but when I click the second time it showed up. What could be the reason of this behavior?

Here is my code:

saveProfile() {
  this.getGeoLocation(this.latitude, this.longitude, (val) => {
    console.log(val)
    l
    if (!val) {
      console.log('val is null')
      this.toastr.error('Latitude  , Logitude is not valid', 'Error')
      return;
    }
    ...
  })
}

Here is my geocoding function:

getGeoLocation(lat: number, lng: number, cb) {
  let geocoder = new google.maps.Geocoder();
  let latlng = new google.maps.LatLng(lat, lng);

  let request = {
    latLng: latlng
  };
  geocoder.geocode(request, (results, status) => {
    console.log(results)
    if (results.length == 0) {
      cb(null)
    }

    if (status == google.maps.GeocoderStatus.OK) {

      let result = results[0];
      console.log(result)
      let rsltAdrComponent = result.address_components;
      for (let ac = 0; ac < rsltAdrComponent.length; ac++) {
        let component = rsltAdrComponent[ac];
        switch (component.types[0]) {
          case 'locality':
            this.cityName = component.long_name;
            break;
        }
      };
      if (result != null) {
        cb(this.cityName);

      } else {
        cb(null);
      }
    }
  });
}

Solution

  • Im using google maps apis which are running outside scope of angular . So it was issue of angular zone. I have used zone run function for this

    this.ngZone.run(() => {
      this.toastr.warning('This latitude and longitude is not found in selected city! fill 
     the correct one')
     })