0

I am trying to use google map API to find hospitals in certain location using this library : https://developers.google.com/maps/documentation/javascript/places.

I succeded to make the request and display result in console but i want to put the result in variable to display it using the ngFor in the html page and that is where i found this problem.enter image description here

Here is my code:

hospSearch_res:any[] = [];
searchHospitals(){
console.log('Search works');
console.log(this.hosp_lat);
console.log(this.hosp_lng);
console.log(this.hosp_rad);

var search_loc = new google.maps.LatLng(this.lat,this.lng);

var request = {
  location: search_loc,
  radius: '1000',
  types: ['hospital']
};

var service = new google.maps.places.PlacesService(document.getElementById('test'));
service.nearbySearch(request, this.callback);

}

callback(results, status) {
  if (status == google.maps.places.PlacesServiceStatus.OK) {
    // this.hospSearch_res = results;
    //let res = JSON.stringify(results);
    console.log(results);
    this.hospSearch_res = results;
    for (var i = 0; i < results.length; i++) {
      var place = results[i];
      //this.hospSearch_res.push(place);
      /*console.log(results[i]);
      console.log(results[i].name);*/

    }

  }
}

This is my first project with angular 2 and i got stcuk for this problem, any help would be much appreciated . Thank you

3
  • It says this is undefined.. Commented Apr 14, 2017 at 14:40
  • Yes that was the error. Karbos reponse solved te problem, thank you anyway Commented Apr 14, 2017 at 20:29
  • Hi, I am new to angular 2. can you please help, how to make service in angular2 for google maps API Commented Jul 21, 2017 at 6:54

1 Answer 1

1

Just replace your callback function by an arrow function to bind this :

var service = new 
google.maps.places.PlacesService(document.getElementById('test'));
service.nearbySearch(request, this.callback);

}

callback = (results, status) => { //Arrow Function Here !
  if (status == google.maps.places.PlacesServiceStatus.OK) {
    ...
  }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the quick response. Apparently i still have a lot to learn in angular 2.

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.