Implementing Google Places reviews on a website with the help of JavaScript

Struggling to display the Google reviews for my company on our website, I can't seem to make it work. I've attempted to use this code:

<script>
    $(function() {
        var people = [];
        $.getJSON('https://maps.googleapis.com/maps/api/place/details/json?placeid=<?php echo $placeId ?>&key=<?php echo $api_key ?>', function(data) {
            $.each(data.reviews, function(i, f) {
                var tblRow = "<tr>" + "<td>" + f.author_name + "</td>" +
                "<td>" + f.rating + "</td>" + "<td>" + f.relative_time_description + "</td>" + "<td>" + f.text + "</td>" + "</tr>"
                $(tblRow).appendTo("#google-reviews");
            });
        });
    });
</script>

I'm looking to receive a response similar to this json file:

{
   "html_attributions" : [],
   "result" : {
      ...
      "rating" : 4.5,
      "reference" : "CmRSAAAAjiEr2_A4yI-DyqGcfsceTv-IBJXHB5-W3ckmGk9QAYk4USgeV8ihBcGBEK5Z1w4ajRZNVAfSbROiKbbuniq0c9rIq_xqkrf_3HpZzX-pFJuJY3cBtG68LSAHzWXB8UzwEhAx04rgN0_WieYLfVp4K0duGhTU58LFaqwcaex73Kcyy0ghYOQTkg",
      "reviews" : [
         {
            "author_name" : "Robert Ardill",
            "author_url" : "https://www.google.com/maps/contrib/106422854611155436041/reviews",
            "language" : "en",
            "profile_photo_url" : "https://lh3.googleusercontent.com/-T47KxWuAoJU/AAAAAAAAAAI/AAAAAAAAAZo/BDmyI12BZAs/s128-c0x00000000-cc-rp-mo-ba1/photo.jpg",
            "rating" : 5,
            "relative_time_description" : "a month ago",
            "text" : "Awesome offices. Great facilities, location and views. Staff are great hosts",
            "time" : 1491144016
         }
      ],
      "types" : [ "point_of_interest", "establishment" ],
      "url" : "https://maps.google.com/?cid=10281119596374313554",
      "utc_offset" : 600,
      "vicinity" : "5, 48 Pirrama Road, Pyrmont",
      "website" : "https://www.google.com.au/about/careers/locations/sydney/"
   },
   "status" : "OK"
}

However, I keep encountering two errors:

https://maps.googleapis.com/maps/api/place/details/json?placeid={placeid}&key={apikey} net::ERR_FAILED
Access to XMLHttpRequest at 'https://maps.googleapis.com/maps/api/place/details/json?placeid={placeid}&key={apikey}' from origin '{the site I work on}' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

Anyone have a solution for this issue?

Answer №1

When using Places Details through a client-side application, it's necessary to utilize the Places Library in Maps JavaScript API. You can find more information in the following docs: https://developers.google.com/maps/documentation/javascript/places

Firstly, you need to include the Google Maps API with the Places library enabled and set up the map container:

<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places"></script>
<body>
    <div id="map"></div>
    <div id="google-reviews"></div>
</body>

Next, execute the request:

<script>
var request = {
  placeId: 'ChIJN1t_tDeuEmsRUsoyG83frY4',
};

service = new google.maps.places.PlacesService(map);
service.getDetails(request, callback);

function callback(place, status) {
  if (status == google.maps.places.PlacesServiceStatus.OK) {
    console.log(place);
        $.each(place.reviews, function(i, f) {
        var tblRow = "<tr>" + "<td>" + f.author_name + "</td>" +
        "<td>" + f.rating + "</td>" + "<td>" + f.relative_time_description + "</td>" + "<td>" + f.text + "</td>" + "</tr>"
        $(tblRow).appendTo("#google-reviews");
    });

  }
}
</script>

For an example, check out this link: https://jsfiddle.net/scarabs/we541sqg/1/

Answer №2

I took a unique approach by creating a file named googleData.php which I scheduled to run twice daily using a cron job. Here is the code snippet:

<?php 
include 'config.php';
$api_key = $config["apikey"];
$placeId = $config["locationId"];
$response = file_get_contents("https://maps.googleapis.com/maps/api/place/details/json?placeid=$placeId&fields=name,rating,reviews&key=$api_key");

$fp = fopen('googleData.json', 'w');
fwrite($fp, $response);
fclose($fp);
?>

This script generated the following JSON response in the file googleData.json:

 {
   "html_attributions" : [],
   "result" : {
      "name" : "Google Place",
      "rating" : 4.7,
      "reviews" : [
         {
            "author_name" : "John Doe",
            "author_url" : "example.com/johndoe",
            "language" : "en",
            "profile_photo_url" : "example.com/johndoepic",
            "rating" : 5,
            "relative_time_description" : "5 months ago",
            "text" : "Very helpful.",
            "time" : 1570537557
         },
         { 
            // Additional review objects omitted for brevity
         }
      ]
   },
   "status" : "OK"
}

Using this data, I created another file called getreviews.php with the following code:

var json = $.getJSON("googleData.json", function(response) {
    var result = response.result;
})

This allowed me to access and display each value from the Google API response.

If anyone is interested, here is what was stored in the config.php file:

<?php
    $config["apikey"] = "YOUR_API_KEY";
    $config["locationId"] = "YOUR_PLACE_ID";
?>

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

Implement a timeout feature for npm clickhouse queries

Is there a way to set the timeout for query execution in the following code snippet? I attempted to use the timeout property, but it does not seem to be functioning as expected. const results = await clickhouse.query(query, { timeout: 50, }).toPromise(); ...

Is there a way to override the JSON.stringify method within the JSON class of a TypeScript project without using a custom call?

Dealing with a React Native and TypeScript app here. I keep encountering an error from Fabric every week: "JSON.stringify cannot serialize cyclic structures." The frustrating part is that the error seems to pop up randomly, without any specific scenario tr ...

Tips for ensuring that a THREE.Group is always displayed in front of other objects

I am attempting to display a set of transform controls in such a way that they are constantly visible to the user. However, when I disable DepthWrite or apply the AlwaysDepth function to the transform controls, I achieve the desired result but encounter an ...

Sharing properties across various components with Next.js

I'm still getting the hang of using Next.js and encountering issues with sharing data between components. Currently, I have a setup involving three components: //index.js function App() { const choices = [] for (let i = 1; i < 101; i++) { ...

Guide on utilizing the JSON string to update and obtain fresh information

My goal is to continuously send a JSON string {"latitude":53.86897577,"longitude":10.66560449,"formatted":"24.04.2015 16:26:35","route":4} to the server every minute, but I keep receiving the same data. How can I ensure that I always get new data in the JS ...

Unclear outcomes from iterative loops

I have a question about this particular for loop: for (var i=0,j=0;i<4,j<20;i++,j++) { a=i+j; } console.log(a); Can someone explain why the output is 38? I initially expected it to be 6. ...

Initialize data only when the Nuxt.js application is first loaded

Exploring the world of nuxt.js, I find myself pondering on the most efficient way to fetch data using REST api. Within my store folder, the structure is as follows: store -posts.js -categories.js -index.js Initially, I attempted to set the da ...

Executing all promises later in Node.js using Promise.all

Having a series of promises set up as follows: module.exports = function (a, b, c) { return someAsync(() => { someFunc(a); }) .then(() => myPromises(a, b, c)) .then(result => { console.log(&apos ...

Is Vue js converting nested objects into strings before returning them?

There is an object in my code var user = { name:"test", number:"9666-0503", details:{ test:"cannot_access_this", second_field:"nope_no_go" } } A call to a Vue JS action is being made [TYPES.FETCH_USER]({ ...

Gathering information from mapped objects when they are clicked in a React application

Do you know how to retrieve genre.id when a user clicks on a Button and triggers the onClick function? Your assistance is greatly appreciated. ... return ( <div className="App"> <Header /> <div className="A ...

Tips for saving the web address and breaking down each word

Hello, I am familiar with how to store URL parameters using the following JavaScript code. However, I am wondering if there is a way to store each word that comes after a slash in a URL. For example, let's consider the URL: http://localhost:9000/Data ...

An exploration on integrating a controller into an Angular directive class using Typescript

Here's the TypeScript code for an Angular directive class I've been working on: I'm wondering how I can incorporate a controller into this directive without creating a separate controller class. My goal is to write and inject the ISOLATE SC ...

Is it possible to resize an image in a single direction?

Is there a way to scale in one direction only? Typically, the scale function will scale the canvas equally in both the x and y directions. But what if I want to scale, for example, a polyline or group of lines only in the x direction without affecting the ...

NodeJS sqs-consumer continuously triggers the function to execute

I have been utilizing the npm package called sqs-consumer to monitor messages in a queue. Upon receiving a new message, I aim to generate a subfolder within an S3 bucket. However, I am encountering a problem where even after the message is processed and re ...

The deployed MVC code encountered an unexpected token "u" in the JSON at position 0

I have a MVC 5 application that is functioning well in the development environment. However, when I publish and deploy it to the testing server (or any other server), I encounter a JavaScript error when clicking on the login button: Uncaught SyntaxError ...

Ensuring the cookie remains active throughout various subdomains

After implementing code to set a cookie on example.com, I noticed an issue with it carrying over to the subdomain dogs.example.com. <script> document.cookie="cid1={{utm_campaign}}; path=/;" </script> The {{}} is part of Google-Tag-Manager s ...

Is there a problem encountered when attempting to pass an array value as a string using props in Vue.js?

<template> <div> <div v-for="piza in pizas" :key="piza.pname"> {{ piza.pname }} <List :content="matchpizza" :pname="piza.pname" :qname="quantitys.qname" /> </div> </div> </template> <scr ...

Accessing WCF REST endpoint using Ajax and transmitting data in JSON format

I have developed a Rest service in WCF (demo), which provides me with the following output: {"GetEmployeeJSONResult":{"Id":101,"Name":"Sumanth","Salary":5000}} Now, I have created an ASP.NET website where I am utilizing AJAX JSON to call this rest service ...

Step-by-step guide to creating a transition effect when the input changes

I'm looking to add a unique effect to my dropdown menu My goal is to create an effect in which the placeholder moves up and the new value seamlessly takes its place, using JS, jQuery, CSS, and HTML. View before transition View after transition ...

The button I have controls two spans with distinct identifiers

When I press the player 1 button, it changes the score for both players. I also attempted to target p2display with querySelector("#p2Display"), but it seems to be recognized as a nodeList rather than an element. var p1button = document.querySelector("# ...