Riadh
Riadh

Reputation: 3

integrating google map api in angular 2

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

Upvotes: 0

Views: 417

Answers (1)

Karbos 538
Karbos 538

Reputation: 3055

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) {
    ...
  }
}

Upvotes: 1

Related Questions