问题描述
我目前一直在尝试从 Google Places API 获取图像,在文档中说明要获取您拥有的图像 https://maps.googleapis.com/maps/api/place/photo?maxwidth=400&photoreference=[imagereference]&key=[yourkey]
这会将您重定向到包含实际图像的 URL。我如何使用 axios 或 fetch 执行此过程,因为我正在尝试获取 base 64 图像版本,以便我可以在我的 React 应用程序中使用?
解决方法
如果您想在客户端应用程序中显示 Places API 照片,您需要使用 Google Maps JavaScript Places Library 的 Places Photos。
下面的代码片段展示了我如何从 getDetails
结果中获取照片 URL 并将其放入我的状态变量中的示例:
const request = {
placeId: "ChIJN1t_tDeuEmsRUsoyG83frY4",fields: [
"name","formatted_address","place_id","geometry","photos"
]
};
const service = new google.maps.places.PlacesService(map);
service.getDetails(request,(place,status) => {
if (
status === google.maps.places.PlacesServiceStatus.OK &&
place &&
place.geometry &&
place.geometry.location
) {
const marker = new google.maps.Marker({
map,position: place.geometry.location
});
}
this.setState({
photos: place.photos[0].getUrl(),name: place.formatted_address
});
});
这是 sample code,要查看这项工作,请将 YOUR_API_KEY
内脚本中的 Map.js
替换为您的 API 密钥。