0

Am unable to display mapLoc value in front end... any help?

Here is my component.ts file

export class mycomponent{

 mapLoc:any;

 constructor(){...}

openImageModal(lat,lng){
 this.mapLoc = '';
 var latlng = new google.maps.LatLng(lat, lng);
        var geocoder = geocoder = new google.maps.Geocoder();
        geocoder.geocode({ 'latLng': latlng }, function (results, status) {
                if (status == google.maps.GeocoderStatus.OK) {
                    if (results[1]) {
                        console.log(results[1].formatted_address); //able to console
                        this.mapLoc = results[1].formatted_address;
                    }
                }
            });
}

this is mycomponent.html file

<ngui-map zoom="{{zoom}}" center="{{lat}}, {{lng}}" (mapReady$)="onMapReady($event,lat,lng)" (mapClick)="onMapClick($event)" (idle)="onIdle($event)">
                <marker *ngFor="let pos of position" [position]="[pos.lat, pos.lng]" draggable="true" (initialized$)="onMarkerInit($event)"></marker>
                    <info-window id="iw">
                        <div *ngIf="marker.display">
                        {{mapLoc}}
                        </div>
                    </info-window>
            </ngui-map>
Esco
  • 387
  • 2
  • 3
  • 16

2 Answers2

0

The value of this can be different inside the callback (To check this, try console.log("this", this) inside the callback.). Try using a big arrow function instead to keep reference to your component.

    geocoder.geocode({ 'latLng': latlng }, (results, status) => {
            if (status == google.maps.GeocoderStatus.OK) {
                if (results[1]) {
                    this.mapLoc = results[1].formatted_address;
                }
            }
        });

or cache a reference and use it in the old way:

    let component = this;
    geocoder.geocode({ 'latLng': latlng }, function (results, status) {
            if (status == google.maps.GeocoderStatus.OK) {
                if (results[1]) {
                    console.log(results[1].formatted_address); //able to console
                    component.mapLoc = results[1].formatted_address;
                }
            }
        });
sabithpocker
  • 15,274
  • 1
  • 42
  • 75
0

That is very common issue of scoping :

Just change :

geocoder.geocode({ 'latLng': latlng }, function (results, status) {

to

geocoder.geocode({ 'latLng': latlng }, (results, status) => {

OR

geocoder.geocode({ 'latLng': latlng }, function (results, status) { ... }).bind(this)

For More Detail Ref : https://stackoverflow.com/a/47278161/2349407

Vivek Doshi
  • 56,649
  • 12
  • 110
  • 122