Fetch data from Google API (Places)

Question:

Hi, I would like to read in data from a company profile via the Google API and extract and output the opening hours.

I have a Google API key and the http request in the browser line returns a json result including opening hours. In Wix, however, I always get my error message “no data” via the function, there seems to be no data delivered?

In my code, instead of COMPANYNAME the company name is written directly and instead of APIKEY my Google Key (as written, the same url directly in the browser returns a result).

Thy for any support!

Product:

Wix Editor

What have you already tried:

I used code examples from wix-fetch - Velo API Reference - Wix.com

My backend code:

export function fetchOpeningHours() {
    const url = encodeURI(`https://maps.googleapis.com/maps/api/place/findplacefromtext/json?input=COMPANYNAME&inputtype=textquery&fields=formatted_address,opening_hours,name&key=APIKEY`);
    fetch(url, {"method": "get"})
    .then( (httpResponse) => {
        if (httpResponse.ok) {
            return httpResponse.json();
        } else {
            console.log ("Fetch did not succeed");
            return Promise.reject("Fetch did not succeed");
        }
    })
  .then(json => console.log("json data: " + json))
  .catch(err => console.log("Fehler: " + err));
}

My frontend code:

printOpeningHours();

async function printOpeningHours() {
    const data = await fetchOpeningHours();
    if (data && data.candidates && data.candidates.length > 0) {
        const openingHours = data.candidates[0].opening_hours;
        if (openingHours && openingHours.weekday_text) {
            openingHours.weekday_text.forEach(day => {
                console.log("Day: " + day);
            });
        } else {
            console.log('Opening hours not available.');
        }
    } else {
        console.log('no data.');
    }
}
});
1 Like

Does it succeed if you set the mode: "cors" option on the fetch request?

fetch(url, {"method": "get", "mode": "cors"})

Hi anthony,

I changed the backend code to…

export function fetchData() {
	const key = "xxxxxxxxxx";
    const GoogleID = "xxxxxxxxx";
    const url = "https://places.googleapis.com/v1/places/" + GoogleID + "?fields=regularOpeningHours,formattedAddress,internationalPhoneNumber,websiteUri,rating&key=" + key
    return fetch (url, {method: 'get'}).then( (httpResponse) => {
	    if (httpResponse.ok) {
	    	return httpResponse.json();
		}
	})
}

Now it works.

Thanks for the reply!