0

I would like to add in an array of objects, but it does not work: Can not set property '0' of undefined

I try to put in this.positions [0] = the PositionMap object

I have decreased the size of the code for better readability, but the rest works

Here is my code:

import { Component, ViewChild, ElementRef } from '@angular/core';
import { NavController } from 'ionic-angular';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { Geolocation } from 'ionic-native';

declare var google;

@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {

  positions: PositionMap[] = [];

  @ViewChild('map') mapElement: ElementRef;

  constructor(public navCtrl: NavController) {
    this.positions = [];
  }

ionViewDidLoad(){
    this.loadMap();
    this.autocomplete();
  }

  autocomplete() {
      autocompleteDepart.addListener('place_changed', function() {
        var place = autocompleteDepart.getPlace();
        let tmpPosition = new PositionMap(place.geometry.location.lat(), place.geometry.location.lng()); 
        this.positions[0] = (tmpPosition); 
        return;
      });
  }
}

export class PositionMap {
  latitude: number;
  longitude: number;
  constructor(_latitude: number, _longitude: number) {
     this.latitude = _latitude;
     this.longitude = _longitude;
  }
}

My table is well declared in the class and in the constructor, but yet is not known in the function.

0

1 Answer 1

2

You're using this from a callback function. This callback function must first be bound to this. The easiest way is to use an arrow function:

autocompleteDepart.addListener('place_changed', () => {
  ...
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.