我开始使用Google Places API工作Angle 6项目。
我们有“ nearbySearch”功能。
我只是想获取来自“ nearbySearch”的“回调函数”的值,并将其保存到名为“ stores”的变量中。
数据确实接收到“结果”回调变量。我只想要它到外面的世界。
我在该回调函数中尝试了很多事情。包括“ this.stores = results”。
什么都没有。似乎“存储变量”从未初始化。我的示例代码如下。
位于“ getStores()”方法中。
map: google.maps.Map;
subscription: Subscription;
dataEmit: Subject<any>;
stores = [];
dataLoaded$ = false;
address: String;
lat = 33.780627;
lon = -84.336754;
filtersLoaded: Promise<boolean>;
constructor(private dataService: DataService, private rest: RestApiService) {}
async ngOnInit() {
this.dataEmit = new Subject();
this.address = this.dataService.getLocation();
this.getLatLong();
this.dataLoaded$ = true;
console.log(this.stores);
console.log(this.stores);
}
async getLatLong() {
const data = await this.rest.get(
`https://maps.googleapis.com/maps/api/geocode/json?address=${
this.address
}&key=MY_API_KEY`
);
this.lat = data["results"][0].geometry.location.lat;
this.lon = data["results"][0].geometry.location.lng;
console.log("lat : " + this.lat + " lon : " + this.lon);
console.log(data);
}
getStores() {
console.log(this.address);
const radius = 2000000;
const keyword = this.dataService.getLocation();
const cur_location = new google.maps.LatLng(this.lat, this.lon);
const request = {
type: "restaurant",
location: cur_location,
radius: radius
};
const pyrmont = new google.maps.LatLng(this.lat, this.lon);
const map = new google.maps.Map(document.getElementById("map"), {
center: pyrmont,
zoom: 15
});
const service = new google.maps.places.PlacesService(map);
service.nearbySearch(request, (results, status) => {
if (status === google.maps.places.PlacesServiceStatus.OK) {
this.dataService.set(results);
if (results) {
for (let i = 0; i < results.length; i++) {
let place = results[i];
this.dataEmit.next(place);
}
this.dataEmit.complete();
}
}
});
}
ngAfterViewInit() {
this.getStores();
console.log("ngAfterViewInit");
this.dataEmit.subscribe(data => {
this.stores = data;
});
console.log(this.stores.length);
}