1

I am working on a method to fetch "photo_reference" from JSON below;

{
   "html_attributions" : [],
   "results" : [
      {
         "formatted_address" : "Bandar Seri Begawan, Brunei",
         "geometry" : {
            "location" : {
               "lat" : 4.903052199999999,
               "lng" : 114.939821
            },
            "viewport" : {
               "northeast" : {
                  "lat" : 4.9665412,
                  "lng" : 115.0004731
               },
               "southwest" : {
                  "lat" : 4.845741299999999,
                  "lng" : 114.8757076
               }
            }
         },
         "icon" : "https://maps.gstatic.com/mapfiles/place_api/icons/geocode-71.png",
         "id" : "b4a5514750d9d7b0164125a220f5c111ae391f4d",
         "name" : "Bandar Seri Begawan",
         "photos" : [
            {
               "height" : 1200,
               "html_attributions" : [
                  "\u003ca href=\"https://maps.google.com/maps/contrib/102574123639894598769\"\u003eSharaf Vallappuzha\u003c/a\u003e"
               ],
               "photo_reference" : "CmRaAAAAKwcyWRgvz9w4IVkWulF7RtNl2bThJaCyfWbOI4hf8oQe-FKwLnpTh5VBbz2ZPo-fBusRkySxNZ2Pf2bfKoL_CljuTg4XnCwLfPxZU24ug-MEdilWgA4umy0nQvnmVs0gEhAFrFECNYCJUhZWvsUgEhRQGhSEcO6jK-mFFKpWXQ24TH15pKoZqQ",
               "width" : 1600
            }
         ],
         "place_id" : "ChIJH3MLVLD1IjIRS-i6fMT4rO4",
         "reference" : "ChIJH3MLVLD1IjIRS-i6fMT4rO4",
         "types" : [ "locality", "political" ]
      }
   ],
   "status" : "OK"
}

Which I obtained by opening this link on the browser.

However my JS code below;

const targetUrl = `https://maps.googleapis.com/maps/api/place/textsearch/json?query=bandar+seri+begawan&key=API-KEY`;
    fetch(targetUrl, {mode: 'no-cors'})
    .then(response => response.json())
.then(function(response) {
        console.log(response.results.photos.photo_reference)
})
.catch(e => {
  console.log(e);
    })
}

and got "SyntaxError: "JSON.parse: unexpected end of data at line 1 column 1 of the JSON data"" error in browser's console.

So i decided to get raw result by removing json() with the code below;

        fetch(targetUrl, {mode: 'no-cors'})
        .then(response => response)
    .then(function(response) {
            console.log(response)
    })
    .catch(e => {
      console.log(e);
        })

Got this error from browser console instead;

Response { type: "opaque", url: "", redirected: false, status: 0, ok: false, statusText: "", headers: Headers, body: null, bodyUsed: false }

It seems that fetch() returned empty. But it is not when URL is keyed into a browser.

Is there some kind of google security feature I need to activate or deactivate? Any thoughts on this will be appreciated.

Gerald Goh
  • 55
  • 5
  • 3
    That's not how to see the raw response. Use `.text()` instead of `.json()`. Also, unless you work at Google a no-cors request to their API will fail... – Jared Smith Feb 16 '20 at 20:39
  • 1
    Thanks for the response Jared. Using `.text()` returned `` and `cors` returned `Cross-Origin Request Blocked`. So I had to use ``no-cors` to get rid of the error. – Gerald Goh Feb 16 '20 at 20:47
  • 2
    Then you can't do it, Google doesn't have cors enabled for that endpoint and you aren't making the call from Google's origin. You get it when you go there directly because the origin is Google but for a fetch request has the same origin as the page it's on – Jared Smith Feb 16 '20 at 20:57
  • That made sense ‍♂️. Thanks again. Guess I will be sourcing for another API enable image site. – Gerald Goh Feb 16 '20 at 21:46
  • 2
    Use the Google Maps Javascript API v3 Places library to access that information from a browser or use the web service from a server. – geocodezip Feb 17 '20 at 02:05
  • May I know your use case why you want to get the value of photo_reference? – Pagemag Feb 19 '20 at 00:16

1 Answers1

0

I guess that the API is only thought for server usage and does not allow client usage. You might want to use the JavaScript API instead.

<script async defer
src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap">
</script>

var service = new google.maps.places.PlacesService(document.getElementById('map'));

Also see:

How to use CORS to implement JavaScript Google Places API request

How to install google maps through npm?

https://developers.google.com/maps/documentation/javascript/overview#js_api_loader_package

Stefan
  • 10,010
  • 7
  • 61
  • 117