Ad

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.

Ad

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.

Ad
source: stackoverflow.com
Ad