问题
I am using the google places api, and I am trying to get an image for a place of a nearby search. I have tried several variations, and it seems like the documentation is not right, or I am doing something that is not obviously wrong.
I have tried this.
let request2 = {
key: this.apiKey.getStandardGoogleKey(),
placeId:"place_id_to_be_used"
};
service.getDetails(request2, (results, status )=> this.callback2(results, status));
}
callback2(results, status){
console.log(results);
}
I get this result
According to the docs, a photos array should include a photo_reference so that I can access an image, but it does not.
I have also tried access the api directly with an http request from angular using this
https://maps.googleapis.com/maps/api/place/nearbysearch/output?parameters
When I do this from postman, I get the photo_reference. But when I do this from my angular app I get a CORS error which looks like this.
I can get around this locally by adding a plugin to chrome, but the error returned on the production server.
My question is. How do I get a photo_refence from the google places api or another google api for a placeid or another value retrieved from a nearbySearch?
回答1:
The photo_reference
property appears in the response of Places API web service. As you mentioned, the web service cannot be called directly from the client side JavaScript code due to same-origin policy of web browsers that results in CORS error.
Looking at your screenshot, I would say that the library you used in your code uses a places service of Maps JavaScript API. So you call getDetails()
method of PlacesService:
https://developers.google.com/maps/documentation/javascript/reference#PlacesService
The callback function receives PlaceResult object:
https://developers.google.com/maps/documentation/javascript/reference#PlaceResult
The place result contains an array of PlacePhoto objects:
https://developers.google.com/maps/documentation/javascript/reference#PlacePhoto
As you can see the PlacePhoto object has a getUrl(opts:PhotoOptions)
method:
Returns the image URL corresponding to the specified options. You must include a PhotoOptions object with at least one of maxWidth or maxHeight specified.
Use this method and you will get a URL of place photo.
I hope this helps!
来源:https://stackoverflow.com/questions/47022354/how-to-get-a-an-image-of-a-place-from-a-nearby-search-from-google-api-with-an-an