简体   繁体   中英

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

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

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