3

I'm using AngularJS with ES6, while implementing ngMap module for the autocomplete feature of google map.

/* html file */
  Enter an address: <br/>
<input places-auto-complete size=80
       ng-model="$ctrl.address"
       component-restrictions="{country:'in'}"
       on-place-changed="$ctrl.placeChanged()"/> <br/>
<div ng-show="$ctrl.place">
  Address = {{$ctrl.place.formatted_address}} <br/>
  Location: {{$ctrl.place.geometry.location}}<br/>
</div>
address : {{$ctrl.address}}
<ng-map></ng-map>

And the javascript file containing component

'use strict';
(function() {

class RateRestaurantsController {
constructor(NgMap) {
  this.NgMap = NgMap;
  this.types = "";
  this.place = "";
  this.address = "";
  this.map = {};


}

$onInit() {

  this.NgMap.getMap().then((map)=> {
    this.map = map;
  });
}

placeChanged(){
 console.log(this); // This refers the [Object] returned by google map api; not to the the constructor(as shown in the image)
  this.place = this.getPlace();
  this.map.setCenter(this.place.geometry.location);

  }

 }

angular.module('gmHotelRatingApp.rateRestaurants')
.component('rateRestaurants', {
  templateUrl: 'app/rate-restaurants/rate.restaurants.html',
  controller: RateRestaurantsController
});

})();

The Object returned which is returned: Image showing 'this' context; which is causing 'this.map' to be undefined

I want 'this.map' and 'this.place' reference to constructor property and 'this.getPlaced()' to fetch the auto complete data. How can I solve this problem?

1

1 Answer 1

2

My solution is:

constructor(NgMap) {

  this.ngMap = NgMap;

  var controller = this;
  this.ngMap.getMap().then((map) => {
      this.map = map;
  });

  this.myCallback = function () {
     controller.place = this.getPlace();
     controller.map.setCenter(controller.place.geometry.location);
  }


}

I know that a function must be outside the constructor but it works for me.

Sign up to request clarification or add additional context in comments.

1 Comment

Works also for me

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.