使用Angular获取Google Place照片的正确URL可以通过以下步骤完成:
@types/googlemaps
和ngx-google-places-autocomplete
这两个依赖包。你可以使用以下命令进行安装:
npm install @types/googlemaps ngx-google-places-autocomplete
import { Component } from '@angular/core';
import { GooglePlaceDirective } from 'ngx-google-places-autocomplete';
import { MapsAPILoader } from '@types/googlemaps';
export class YourComponent {
placePhotoUrl: string;
// 其他代码...
}
ngOnInit
生命周期钩子中,初始化Google Maps服务并加载Places API:
export class YourComponent implements OnInit {
// 其他代码...
constructor(private mapsAPILoader: MapsAPILoader) {}
ngOnInit() {
this.mapsAPILoader.load().then(() => {
// 初始化完成后,可以使用Google Maps服务
});
}
}
google.maps.places.PlacesService
来获取Google Place的照片URL。在你需要获取照片的地方,添加以下代码:
const placeService = new google.maps.places.PlacesService(document.createElement('div'));
const request = {
placeId: 'YOUR_PLACE_ID', // 替换为你要获取照片的Google Place的ID
fields: ['photos']
};
placeService.getDetails(request, (place, status) => {
if (status === google.maps.places.PlacesServiceStatus.OK) {
if (place.photos && place.photos.length > 0) {
const photoUrl = place.photos[0].getUrl({ maxWidth: 500 }); // 设置照片的最大宽度
this.placePhotoUrl = photoUrl;
}
}
});
请确保将YOUR_PLACE_ID
替换为你要获取照片的Google Place的实际ID。
placePhotoUrl
变量来显示照片:
<img src="placePhotoUrl" alt="Google Place Photo">
这样,你就可以使用Angular获取Google Place照片的正确URL了。记得替换YOUR_PLACE_ID
为实际的Google Place ID,并根据需要调整照片的最大宽度。
领取专属 10元无门槛券
手把手带您无忧上云