Poonam
Poonam

Reputation: 149

Uncaught TypeError: Cannot read property 'push' of undefined while pushing data in public array

I am trying to push some values in array on function call. I got the vaues in function but when I am trying to push those values in array I am getting the error Cannot read property 'push' of undefined. However I have initialize the array as public as per the typescript format. Yet, I am unable to find where I am doing mistake. I am new to angular so please pardon for silly errors.

    export class AppHome
    {
      public pick_markers:Array<object> = [];
      public dest_markers:Array<object> = [];   

      constructor(private mapsAPILoader: MapsAPILoader, private ngZone: NgZone) {}

      ngOnInit() {
        this.codeAddress('Av. da Liberdade, 1250-096 Lisboa, Portugal','pickup');
      }

      codeAddress(address: string,type) {
        console.log(address);
        var geocoder = new google.maps.Geocoder();
        let latlng:any;
        geocoder.geocode({ 'address': address }, function (results, status) {
          console.log(status);
          if (status == google.maps.GeocoderStatus.OK) {
            let get_lat = results[0].geometry.location.lat();
            let get_lng = results[0].geometry.location.lng();
            if(type=='dest') {
              this.dest_markers.push({lat:+get_lat,lng:+get_lng});
              console.log(this.dest_markers);                       
            } else if(type='pickup') {
              this.pick_markers.push({lat:+get_lat,lng:+get_lng});
              console.log('pickuplatlng--lat::'+this.lat+',,,lng::'+this.lng);
            } else {
              console.log('no input');
            }
          } else {
            alert("Request failed.")
          }
        });
      }
    }

Upvotes: 0

Views: 254

Answers (3)

Tiep Phan
Tiep Phan

Reputation: 12596

you are pointing wrong this, using arrow function or store context as following examples:

    export class AppHome
    {
      public pick_markers:Array<object> = [];
      public dest_markers:Array<object> = [];   

      constructor(private mapsAPILoader: MapsAPILoader, private ngZone: NgZone) {}

      ngOnInit() {
        this.codeAddress('Av. da Liberdade, 1250-096 Lisboa, Portugal','pickup');
      }

      codeAddress(address: string,type) {
        console.log(address);
        var geocoder = new google.maps.Geocoder();
        let latlng:any;
        geocoder.geocode({ 'address': address }, (results, status) => {
          console.log(status);
          if (status == google.maps.GeocoderStatus.OK) {
            let get_lat = results[0].geometry.location.lat();
            let get_lng = results[0].geometry.location.lng();
            if(type=='dest') {
              this.dest_markers.push({lat:+get_lat,lng:+get_lng});
              console.log(this.dest_markers);                       
            } else if(type='pickup') {
              this.pick_markers.push({lat:+get_lat,lng:+get_lng});
              console.log('pickuplatlng--lat::'+this.lat+',,,lng::'+this.lng);
            } else {
              console.log('no input');
            }
          } else {
            alert("Request failed.")
          }
        });
      }
    }

or:

    export class AppHome
    {
      public pick_markers:Array<object> = [];
      public dest_markers:Array<object> = [];   

      constructor(private mapsAPILoader: MapsAPILoader, private ngZone: NgZone) {}

      ngOnInit() {
        this.codeAddress('Av. da Liberdade, 1250-096 Lisboa, Portugal','pickup');
      }

      codeAddress(address: string,type) {
        console.log(address);
        var geocoder = new google.maps.Geocoder();
        let latlng:any;
        const self = this; // <= store context
        geocoder.geocode({ 'address': address }, function (results, status) {
          console.log(status);
          if (status == google.maps.GeocoderStatus.OK) {
            let get_lat = results[0].geometry.location.lat();
            let get_lng = results[0].geometry.location.lng();
            if(type=='dest') {
              self.dest_markers.push({lat:+get_lat,lng:+get_lng});
              console.log(this.dest_markers);                       
            } else if(type='pickup') {
              self.pick_markers.push({lat:+get_lat,lng:+get_lng});
              console.log('pickuplatlng--lat::'+this.lat+',,,lng::'+this.lng);
            } else {
              console.log('no input');
            }
          } else {
            alert("Request failed.")
          }
        });
      }
    }

for better, you could define an interface to declare the shape of object like this:

interface Coords {
  lat: number;
  lng: number
}

public pick_markers:Array<Coords> = [];
public dest_markers:Array<Coords> = [];

for more solutions, please read this thread: Ionic 2 : Set interval

Upvotes: 1

ANSALKHAN K A
ANSALKHAN K A

Reputation: 1

I think the problem is with the array declaration.

try,

pick_markers: any[];
dest_markers: any[];

this.pick_markers.push('data');
this.dest_markers.push('data');

Upvotes: 0

Shubham Azad
Shubham Azad

Reputation: 796

This error occurs because of wrong initialization of an array.

Initialize Array like this, it will work

 dest_markers :Array<any>=[];
 pick_markers :Array<any>=[];

Upvotes: 0

Related Questions