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

Is there a way to automatically send users to a different PHP file once they click "submit"?

I need to redirect to a different php file named index2.php. The username and password values are already set as follows: Username=sid, Password=yeaoklogin. When the user clicks on the Login button, they should be redirected to a page called index2.php. ...

Ways to showcase a JSON menu with a single level

I have a json file containing links to all the images in a specific folder, as shown below: ["http://img1.png","http://img2.png","http://img3.png","http://img4.png"] I would like to create a <ul> list using this data, but I'm not sure how to d ...

"When working with Vue projects, an error may occur stating "Parsing error: No babel config file detected" if the IDE is not opened at

Encountered an issue in VS Code with a Vue project, where if the project is not opened at the root directory, babel.config.js fails to load causing confusion for the IDE. All my files display an error on the initial character of any javascript/vue file st ...

Is there a way to automatically change the value of one input box to its negative counterpart when either of the two input boxes have been filled in?

Consider two input boxes: box1 box2 If a user enters a number in one of the input boxes, we want the value of the other input box to automatically change to the opposite sign of that number. For example: User enters 3 in box1. The value of box2 shoul ...

The Node.js application that uses Express and connects to a MSSQL database is reporting that the database

One of my other applications utilizes express and routes, but for this new app I wanted to simplify it. Despite being confident in the correctness of the connection string, I encountered an issue. script.getQuestions(connection); script.getQuestions = fu ...

Steps to develop a runnable Express API

After developing a basic yet fully functional Node.js Express API application using JavaScript, I am now looking to convert it into an executable file that can be run on Windows systems. The main reason behind this is to provide clients with the option of ...

"Headers cannot be set once they have been sent to the client... Error handling for unhandled promise rejection

Having trouble with cookies in the header - specifically, encountering an error at line number 30. The error message reads: "Cannot set headers after they are sent to the client." Additionally, there is an UnhandledPromiseRejectionWarning related to a prom ...

displaying a pair of inputs next to each other

Is it possible to display two input fields side by side? I am using Angular's matInput forms, but struggling to position the second input next to the first. What I would like to achieve is to have "input1 , input2" on the same line. Here is my code: ...

Tips for making jQuery DataTables switch between multiple DOM tables?

I am working on a project where I need to display different jQuery Datatables based on the selected option in a <select> element. The data for each Datatable is stored in hidden DOM <table> elements: <!-- Make sure jquery.dataTables.css and ...

Substitute this.bindMethod for function component

I have a class component that is structured like this: interface MyProps { addingCoord: any resetCoords: any } interface MyState { x: any y: any } class DrawerOld extends React.Component<MyProps, MyState> { width: number height: number ...

Passing no data in Angular.js ui-router.Angular.js ui-router

Within my Ionic application, there is a need to pass parameter(s) from one sub-view to another. Initially, the parameters are successfully passed as expected. However, upon returning to the first sub-view and then navigating to another sub-view, the parame ...

Is there a way to position the tooltip above the sorter icon in Ant Design (antd) component?

I'm currently working on creating a table with sorter columns using the antd framework. Can anyone guide me on how to position the tooltip above the sorter icon? Below is a snippet of my UI. Specifically, I included this property within the 'dat ...

"Modifying state within a child component and utilizing the refreshed value in the parent component

I'm currently working on creating a simple header mini cart with a cart item counter in NextJS. I'm utilizing the form state value in the header component and then passing that value to the child components of the header where the numerical quant ...

Concealing Components using Angular's ng-change Feature

I need help displaying or hiding an element in a form using ng-change or any other method you suggest. Here is the HTML snippet I am working with: <div ng-app ng-controller="Controller"> <select ng-model="myDropDown" ng-change="changeState( ...

Change the value of the material slide toggle according to the user's response to the JavaScript 'confirm' dialogue

I am currently working on implementing an Angular Material Slide Toggle feature. I want to display a confirmation message if the user tries to switch the toggle from true to false, ensuring they really intend to do this. If the user chooses to cancel, I&ap ...

Change from using fs.writeFileSync to fs.writeFile

I have a question about changing fs.writeFileSync to fs.writeFile const users = { "(user id)": { "balance": 28, "lastClaim": 1612012406047, "lastWork": 1612013463181, "workersCount": 1, ...

What is the reason behind HTML5Boilerplate and other frameworks opting for a CDN to host their jQuery files

When it comes to loading jQuery, HTML5Boilerplate and other sources[citation needed] have a standard process that many are familiar with: <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> <script>window. ...

Responsive Alignment of Slanted Edges using CSS

I have been working on creating a responsive diagonal layout with slanted shapes (refer to the image attached). However, I'm facing a challenge with aligning the edges smoothly at different screen sizes, especially when the rows grow and the screen re ...

What is the process for converting Flask request JSON data into a dictionary?

Struggling with integrating JQuery ajax methods and Flask, attempting to make an ajax call to retrieve a form. The JavaScript code I have written is: $.ajax({ type: 'POST', url: '/projects/dummyName', data: JSON.s ...

What is the process for creating a JSON message to be sent using Amazon SES?

Whenever I attempt to send an email using Amazon-SES, I keep encountering the following error: Error encountered while parsing parameter '--raw-message': JSON is invalid. A property name enclosed in double quotes is expected: line 1 column 2 (cha ...