Google Places Photo API Returns An Image, However, I Am Not Sure How To Send It To My Frontend
If I were to paste this URL in the browser, the API indeed returns an image:
https://maps.googleapis.com/maps/api/place/photo?
maxwidth=400&photoreference=examplereference&key=examplekey
Keep in mind I have removed photoreference because it is too long and the secret key because it should be private.
After getting the image using PHP, I can't seem to send anything I can work with to my front end.
$getImage = file_get_contents("https://maps.googleapis.com/maps/api/place/photo?maxwidth=400&photoreference=examplereference&key=examplekey");
$image = json_decode($getImage);
return response()->json([
'message' => 'Fetched sight!',
'image' => $image
], 201);
If I try to send $image
to the front-end it returns NULL and if I try to send $getImages
, I get an error "Malformed UTF-8 characters, possibly incorrectly encoded"
.
Even after reading the documentation - https://developers.google.com/places/web-service/photos , I can't figure out what am I expected to receive from that request.
Answer
If you want to give an image content with a JSON API endpoint, you can base64 it's content.
<?php
$getImage = file_get_contents("https://maps.googleapis.com/maps/api/place/photo?maxwidth=400&photoreference=examplereference&key=examplekey");
$image = base64_encode($getImage);
return response()->json([
'message' => 'Fetched sight!',
'image' => $image
], 201);
On client side you can create image like this :
<img src="data:image/png;base64, <image content here>" />
Beware the client will perform some extra operations to create the image (not optimized for large image content).
Another solution could be to download the image with your backend and serve it with a classic URL from your server.
Related Questions
- → "failed to open stream" error when executing "migrate:make"
- → October CMS Plugin Routes.php not registering
- → OctoberCMS Migrate Table
- → OctoberCMS Rain User plugin not working or redirecting
- → October CMS Custom Mail Layout
- → October CMS - How to correctly route
- → October CMS create a multi select Form field
- → October CMS - Conditionally Load a Different Page
- → How to disable assets combining on development in OctoberCMS
- → October CMS - Radio Button Ajax Click Twice in a Row Causes Content to disappear
- → OctoberCms component: How to display all ID(items) instead of sorting only one ID?
- → In OctoberCMS how do you find the hint path?
- → How to register middlewares in OctoberCMS plugin?