简体   繁体   中英

Angular 2 - display value from an event listener function in the view via class property

I'm working with ionic 2/angular 2 and google maps.

i have a class

    import {Page, Platform} from  'ionic-angular';
    import {Geolocation} from 'ionic-native';
    import {Http, Response} from '@angular/http';

    @Page({
        templateUrl: 'build/pages/mapPage/mapPage.html',
    })

    export class MapPage {

        date: String = new Date().toISOString();
        address: any = 'Pick a place';

        constructor(private platform: Platform, private http: Http) {
            this.platform = platform;
            this.initializeMap();
        }


        initializeMap() {
        let HTTPP = this.http;
        this.platform.ready().then(() => {
            var myLatLng = {};
            var image = 'custom/img/map-marker-small.png';

            Geolocation.getCurrentPosition().then(pos => {
                myLatLng = { lat: pos.coords.latitude, lng: pos.coords.longitude };                 
            })
                .then(() => {
                    var minZoomLevel = 17;

                    var map = new google.maps.Map(document.getElementById('map_canvas'), {
                        zoom: minZoomLevel,
                        center: myLatLng,
                        mapTypeId: google.maps.MapTypeId.ROADMAP
                    });
                });

             var getAddress = function (lat, lng) {
                    let mapUrl = 'https://maps.googleapis.com/maps/api/geocode/json?latlng=' + lat + ',' + lng + '&key=XXXXXXXXX';  // URL to web API
                    let address = "";

                    return HTTPP.get(mapUrl)
                        .toPromise()
                        .then(data => {
                            let data2 = data.json().results;                                
                            data2[0]['address_components'].forEach(add => {
                                address += add.long_name + ", ";
                            });
                            return address;
                        });
                }

                marker.addListener('dragend', function (event) {
                    var lat = event.latLng.lat();
                    var lng = event.latLng.lng();

                    console.log("lat: " + lat + ", lng: " + lng);

                    getAddress(lat, lng)
                    .then(function(address){
                        console.log(address); //WORKS CORRECTLY
                        //but can't access `this` here. 
                        //this.address = address //THIS IS WHAT I WANT 
                        return address;
                    })

                });
           });
         }
      }

What i want to accomplish is to get the address of the marker that has been dragged to a coordinate and display it to the user in the front end

 <ion-navbar *navbar>
  <ion-title>
    Map Example
  </ion-title>
</ion-navbar>

<ion-content class="home">
  <div id="map_canvas" style="height: 60%"></div>
  <ion-item>
    <ion-label>Date</ion-label>
    <ion-datetime displayFormat="DDD MMM DD, h:mm A" pickerFormat="DDD DD MMM h mm A" [(ngModel)]="date"></ion-datetime>

  </ion-item>
  <ion-item>
   {{address}}
  </ion-item>
</ion-content>

When the marker is dragged i have successfully gotten the coordinates and have successfully gotten the address string. But the this operator is not available in the event listener function for the dragend event of the marker.

How can i equate this.address to my address that i got inside the event listener?

I have tried to make a general refrence to this by doing let self = this; and then using self.address = address inside the function in hopes that it would reflect in the view. but it didn't work.

All i want to do is to display the address in the front end when the user drags the marker to a new location.

Any help would be appreciated thanks!!

Change

function (event) {

to

(event) => {

to retain the scope of this

See also https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Functions/Arrow_functions

There are two places where you lose context: dragend event handler and then callback function. Use arrow function for both of them, this will preserve lexical scope:

marker.addListener('dragend', event => {

  var lat = event.latLng.lat();
  var lng = event.latLng.lng();

  getAddress(lat, lng)
    .then(address => this.address = address);

}); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM