When using the Google Maps API fetch() method, the response is empty. However, when accessing the same

I am currently working on extracting the "photo_reference" from the JSON data provided 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-MEdilWgA4umy0nQvnmVs0gEhAFrFECNYCJUhZWvsUgEhRQGhSEcOjFed2pgTZBVDp1xEs-YIrWX",
               "width" : 1600
            }
         ],
         "place_id" : "ChIJH3MLVLD1IjIRS-i6fMT4rO4",
         "reference" : "ChIJH3MLVLD1IjIRS-i6fMT4rO4",
         "types" : [ "locality", "political" ]
      }
   ],
   "status" : "OK"
}

To access this data I used this link in my browser.

However, when attempting to retrieve the photo reference with my JavaScript 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);
    })
}

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

To troubleshoot, I removed the json() method as shown below:

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

This produced a different error in the browser console:

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

It seems like the fetch() function returned empty. However, entering the URL directly into a browser does yield results.

Could there be a security setting related to Google that needs adjustment? Any insights on this issue would be greatly appreciated.

Answer №1

It seems like the API is intended for server-side use only and may not be suitable for client-side usage. You may want to consider utilizing 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'));

For more information, you can also check out:

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How can we prevent the continual overwriting of Object values?

I'm currently working on extracting data from the USDA Food Data Central API. Specifically, I'm interested in retrieving the "name" and "amount" values under the "nutrient" section. The excerpt below shows the information retrieved: Input- repor ...

Mastering the Art of Trimming with Jquery

function DisplayDataForEdit(id) { $("#editContainer").slideDown("medium"); var parentId ='item'+ id; var colIndex = 0; var $row = $("#" + parentId).parent().parent(); $row.find('td').each(f ...

Working with the Enter Key in Vue.js

I am faced with a challenge involving a text field and a button setup. By default, the button is set to submit a form when the Enter key is pressed on the keyboard. My goal is to capture each key press while someone is typing in the text field, particularl ...

SQL inputs with information that updates automatically / autofill SQL input boxes

Is it feasible to create a webpage that can connect to an SQL database, retrieve information from a table, and display it in a text box based on the input provided in another text box? Essentially, I am looking for a way to enable autofill functionality. I ...

Fill up mongoose with data on 3 schemas

I have successfully populated 2 schema, but I am facing difficulty in populating the third schema. Here are the schemas: Member Schema var mongoose = require('mongoose'); var bcrypt = require('bcryptjs'); var Schema = mongoose.Schema ...

Two approaches for one single object

I'm trying to figure out why this particular code works // ....................................................... var character = { name: 'Joni', type: 'blond', sayName: function() { return this.name; }, sayT ...

A step-by-step guide on harnessing the power of RPG.J

Attempting to utilize the RPG.js library as it appears to be quite powerful. I checked out the official tutorial but am struggling to understand certain aspects, particularly State 4: "Initialize the canvas in your JS file." Any guidance on which one to ...

Matching patterns with regular expressions in Javascript

There's a string that goes like this: |Africa||Africans||African Society||Go Africa Go||Mafricano||Go Mafricano Go||West Africa|. I'm attempting to craft a regular expression that will only match terms containing the word Africa or any variation ...

Refresh database records

I am currently using grails and I am exploring ways to update my database table utility by selecting values from two drop down menus. These drop down menus are populated with values from the database based on user selections from another drop down menu. My ...

Transforming JSON data in Node JS according to the city

I currently have a JSON object that contains information about various products and their details in different cities. const data = [ { "city name": "Chennai", "product name": "Apple", ...

Deleting a DOM element within an element that has been created by an external script

On a webpage, I have third-party ad content that is generated by an external script. This content has a delay in loading. My goal is to eliminate a line break from the ad content, but this can only be done once the external script finishes loading and all ...

Assigning the style of the parent element based on the child element

Currently, I am attempting to develop a customized dropdown field and here is the code I have come up with: const list = document.querySelector('.list'); const listItems = list.getElementsByTagName('p'); document.querySelector('# ...

Exploring AngularJS with Filtering for Advanced Search Results

Currently, I have a search box that successfully searches values in a table using my code. <tr ng-repeat="b in bugs | filter:searchText"> Now, I want to take it one step further by allowing users to search specific columns if they include a colon i ...

Use angular-resource to add a new entry to the db.json file

I have a JSON file called db.json with the following structure: { "menu":[ { "id":0, "item":"item1" },{ "id":1, "item":"item2" },{ "id":2, "item":"item3" } ], "feedback":[] } Currently, I am using Angular's $resource to send a Jav ...

What is the best way to set the value of the days in a month to a div

I've been experimenting with creating a calendar using javascript, HTML, and CSS on my own. I managed to achieve some functionality like obtaining the current month and year as well as the previous month and year by clicking a button in HTML. However, ...

Incorporate fresh Google sites into different web pages using iFrame integration

Wishing you a fantastic day! I am currently working on embedding a brand new Google site into another webpage. I attempted to use an iframe for this purpose, but unfortunately it did not work as expected. Here is the code snippet: <iframe width="1280 ...

The "Open in new tab" feature seems to be missing for links when using Safari on iOS

My webapp contains links structured like this: <a href="/articles/">Articles</a> I am using JavaScript to control these links within my app: $(document).on("click", 'a', function(ev) { ev.preventDefault(); ev.stopPropagat ...

Ways to implement distinct values for model and input field in Angular 5

I'm currently working on an Angular 5 application and I have a requirement to format an input field with thousand separators (spaces). However, the model I am using only allows numbers without spaces. Since my application is already fully developed, ...

Encountering an issue following the installation and integration of an npm module within a Meteor

I recently started a project using the latest version of Meteor. I added a new package by running the command: meteor npm install --save name_of_package Since this package is meant for the client side, I created a file called mypackage.js inside the /cli ...

Transforming images with Imagick

I've been trying to generate thumbnails from PDF uploads using Imagick. I have a script that is supposed to handle this task, but unfortunately, it only uploads the file without creating a thumbnail. I know some of you may find this basic, but PHP is ...