Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call my function from the google.maps.event.listener

My component written in typescript for a page in my Ionic2 project has the follwing structure:

import { Component, ViewChild, ElementRef } from '@angular/core';
...
declare var google;

@Component({
    selector: 'page-search',
    templateUrl: 'search.html'
})

export class SearchPage {
    @ViewChild('map') mapElement: ElementRef;
    map: any;
    guideList: Array<Guide>;
    text: any;
    lat : any; 
    lon : any;

    constructor(public navCtrl: NavController, public recoshService: Recosh, public alertCtrl: AlertController) {
        ...
    }

    ngOnInit(){ 
        this.loadMap();
    }

    loadGuides() {
        ...
    }

    setLat(l){
        this.recoshService.setLat(l);
        this.lat = l;
    }

    setLon(l){
        this.recoshService.setLon(l);
        this.lon = l;
    }

    setPos(lat, lon){
        this.setLon(lon);
        this.setLat(lat);
        this.loadGuides();
    }

    loadMap(){
        ...

        let marker = new google.maps.Marker({
            position: this.map.getCenter(),
            icon: {
                path: google.maps.SymbolPath.BACKWARD_CLOSED_ARROW,
                scale: 5,
                strokeWeight:2,
                strokeColor:"#B40404"
            },
            draggable:true,
            map: this.map,
        });

        google.maps.event.addListener(marker, 'dragend', function() {

            this.setPos(marker.getPosition().lat(),marker.getPosition().lng());

        });
    }
}

But Inside the google.maps.event.addListener(){..} I cant reach the setPos() declared inside my SearchPage class. How can I call this function considering my structure?

like image 916
pittuzzo Avatar asked Dec 10 '22 12:12

pittuzzo


1 Answers

You need to use arrow functions like this:

google.maps.event.addListener(marker, 'dragend', () => {
    this.setPos(marker.getPosition().lat(),marker.getPosition().lng());
});

By using arrow functions, the this property is not overwritten and still references the component instance.

like image 132
sebaferreras Avatar answered Dec 13 '22 22:12

sebaferreras