seyid yagmur seyid yagmur - 1 month ago 23
Node.js Question

ionic 2 undefined is not an object error

I am new in ionic 2.I've encountered a problem.once I use

map
defining
var map;
it is working inside
loadMap()
function well. But if I define map like
map:any;
It is not working.Throwing an error like this.


Error: Uncaught (in promise): TypeError: undefined is not an object
(evaluating 'this.map')


import { Component } from '@angular/core';
import { NavController,Platform } from 'ionic-angular';
import { Geolocation } from 'ionic-native';
import {DataService} from '../../providers/data-service';
declare var L:any;
@Component({
selector: 'page-my-map',
templateUrl: 'my-map.html',
providers:[DataService]
})
export class MyMap {
public data: any;

map:any=null;
markersLayer;

myPositionLayer;
myCircleLayer;
showingon;
LeafIconMe;
LeafIcon;


constructor(platform: Platform, public dataService: DataService) {

platform.ready().then(() => {

Geolocation.getCurrentPosition().then((resp) => {
});

this.loadMap();
this.loadData();

});


}

loadMap(){

this.map = L.map('map', {}).setView([40.980963, 29.0966243], 10);
L.tileLayer(tileURL, {
maxZoom: 18,
attribution: ''
}).addTo(this.map);
this.map.locate({ setView: true, maxZoom: 16 });


this.dataService.getData()
.then(data => {

this.data = data;
this.data.forEach(function(veri){
console.log(veri.lat);
L.marker([veri.lat, veri.lon]).addTo(this.map);

})

});
console.log("map"+this.map);
}
loadData(){
console.log("data"+this.map);




}


}


my npm list is like below.

npm list --depth=0
msson@ /Users/baris/ionic2/denden/msson
├── @angular/common@2.0.0
├── @angular/compiler@2.0.0
├── @angular/compiler-cli@0.6.2
├── @angular/core@2.0.0
├── @angular/forms@2.0.0
├── @angular/http@2.0.0
├── @angular/platform-browser@2.0.0
├── @angular/platform-browser-dynamic@2.0.0
├── @angular/platform-server@2.0.0
├── @ionic/app-scripts@0.0.36
├── @ionic/storage@1.0.3
├── ionic-angular@2.0.0-rc.1
├── ionic-native@2.2.3
├── ionicons@3.0.0
├── rxjs@5.0.0-beta.12
├── typescript@2.0.3
└── zone.js@0.6.21


can u please give me any suggestion to solve this problem. thank in advance..

Answer
this.data.forEach(function(veri){
    console.log(veri.lat);
    L.marker([veri.lat, veri.lon]).addTo(this.map);
})

You need to use an arrow function (instead of function) to retain this context

this.data.forEach((veri) => {
    console.log(veri.lat);
    L.marker([veri.lat, veri.lon]).addTo(this.map);
})
Comments