Nextjs google places autocomplete not providing accurate suggestions

I'm attempting to utilize Google autocomplete to retrieve the names of mosques specifically in the United Kingdom. However, the data I am receiving is global and not limited to mosques. Here is my code:

import axios from "axios";

export default async function GetMosques(req, res) {
  console.log(req.body.input);
  const input = req.body.input;
  const apiKey = "mykey"; // Replace with your actual API key
  const apiUrl = "https://maps.googleapis.com/maps/api/place/autocomplete/json";

  try {
    const response = await axios.get(apiUrl, {
      params: {
        input,
        key: apiKey,
        types: "mosque", // Set the type to "mosque" to filter results to mosques
        componentRestrictions: {
          country: "uk",
        },
      },
    });

    console.log("server:", response.data.predictions);
    

    const predictions = response.data.predictions.map((prediction) => ({
      id: prediction.place_id,
      name: prediction.description,
    }));

    res.json(predictions);
  } catch (error) {
    console.error("Error fetching autocomplete suggestions:", error.message);
    res.status(500).json({ error: "Internal Server Error" });
  }
}

The data I'm receiving is:

{
    description: 'Sayedabad Bus Terminal Masjid, Dhaka - Mawa Hwy, Dhaka, Bangladesh',
    matched_substrings: [ [Object] ],
    place_id: 'ChIJubFsVbO5VTcRRpdyaZ6sXjE',
    reference: 'ChIJubFsVbO5VTcRRpdyaZ6sXjE',
    structured_formatting: {
      main_text: 'Sayedabad Bus Terminal Masjid',
      main_text_matched_substrings: [Array],
      secondary_text: 'Dhaka - Mawa Hwy, Dhaka, Bangladesh'
    },
    terms: [ [Object], [Object], [Object], [Object] ],
    types: [
      'mosque',
      'place_of_worship',
      'point_of_interest',
      'establishment'
    ]
  },
  {
    description: 'Sharjah Mosque - Sharjah - United Arab Emirates',
    matched_substrings: [ [Object] ],
    place_id: 'ChIJGb39ZXqL9T4ReU5jj0N0q6c',
    reference: 'ChIJGb39ZXqL9T4ReU5jj0N0q6c',
    structured_formatting: {
      main_text: 'Sharjah Mosque',
      main_text_matched_substrings: [Array],
      secondary_text: 'Sharjah - United Arab Emirates'
    },
    terms: [ [Object], [Object], [Object] ],
    types: [
      'mosque',
      'place_of_worship',
      'point_of_interest',
      'establishment'
    ]
  }

The 'types' field is correct as it includes mosque, but everything else seems incorrect. The mosque names are missing and the data is from other countries.

Answer №1

Your parameter usage needs adjustment, see the updated version below:

const newResponse = await axios.get(apiUrl, {
      params: {
        userInput: enteredInput,
        securityKey: userApiKey,
        category: "temple", 
        location: "country:uk", // Specify UK as the country
      },
    });

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

Guide on transferring binary image data to a JavaScript function

I have $comment->image_data as the binary data of the image and I want to pass this data to the imgclick() function. Attempting the method below, but encountering an unexpected token error. <img src="data:image/jpg;base64,'.$comment->image_t ...

Ways to verify the occurrence of a successful event following the execution of a save() operation on a model

Below is the snippet of code I am using to store extra properties in a model (specifically, the answer model) selectMedia: => # Post media to server @options.answer.id = @options.answer.get('_id') @options.answer.url = "/v1/answers/#{@o ...

justify-content property seems to be ineffective when used in Chakra UI

Currently in the process of developing a website using Next.js and Chakra-ui. I'm facing some issues with aligning the ButtonGroup to the end of the container. Despite trying to use justifyContent="space-between", it doesn't seem to be ...

What could be causing the data-title attribute to not update in AngularJS?

When utilizing AngularJS and Bootstrap's popover, I have successfully bound to data-content, but am encountering issues with binding to data-title: <li data-trigger="hover" data-placement="bottom" data-title="{{'Memory limit' | l10n}}" d ...

JavaScript random number functionality experiencing an unexpected problem

function generateRandomNumbers(){ var max = document.getElementById('max').value; var min = document.getElementById('min').value; var reps = document.getElementById('reps').value; var i; for (i=0; i<reps ...

Creating Canvas dimensions to match the dimensions of a rectangle specified by the user

When the code below runs, it correctly generates a rectangle the same size as the canvas on start-up. However, an issue arises when the user clicks the button to generate a new canvas - the rectangle does not appear. Can someone please provide assistance ...

Properly executing a for loop

I have devised a method to transform Swagger 1 documentation into Swagger 2. This involves utilizing an array of resources as input for the conversion process. However, I have encountered an issue where the code seems to be skipping ahead and jumping to ...

The error message "cb does not have a callable function"

Having trouble with the same cb is not a function error. Here's what's going on: TypeError: cb is not a function I recently started learning javascript, following tutorials on youtube and trying to apply the code they use for my own project. It ...

Toggle visibility of div based on current business hours, incorporating UTC time

UPDATE I have included a working JSFiddle link, although it appears to not be functioning correctly. https://jsfiddle.net/bill9000/yadk6sja/2/ original question: The code I currently have is designed to show/hide a div based on business hours. Is there a ...

Leveraging Vue 2.0 and webpack to integrate components from an npm package

As I venture into setting up a project with webpack and Vue 2.0, I encountered a slight hiccup when trying to incorporate components from npm packages (such as vue-parallax) into my project. Upon installing the package, everything seems to be in place, bu ...

I prefer not to have the entire URL visible to me

function updateDate(day, month, year) { month += ""; if (month.length <= 1) month = "0" + month; document.location.href = "<?php $_SERVER['PHP_SELF'];?>?page=events&day=" + day + "&month=" + m ...

The window.open() function is malfunctioning on Google Chrome

Within my vue.js application, I have encountered an issue when attempting to utilize window.open() to open a new tab. Strangely, whenever I use this method, the new tab opens briefly before immediately closing without loading any content. Surprisingly, win ...

Delete the entry with the specified unique identifier "this text" from the MongoDB database

So, I've been searching high and low but still can't seem to figure out how to get this to work. Here's the issue I'm facing: I'm currently working on a chat application using node/express/socketio, and I'm attempting to crea ...

Can the functionality of a button be disabled after being clicked a total of 5 times?

Once a user clicks the button five times, I plan for it to be disabled. Can this be achieved solely with HTML, or would JavaScript be necessary? ...

The arrangement of imports in NodeJS can lead to unexpected errors

Having an issue with the order in which I include different models in my main server.js file using NodeJS. Below is the code from my product.js Product model file: var mongoose = require("mongoose"); var Dealer = require("./dealer.js") var productSc ...

Is it possible to ensure that an asynchronous function runs before the main functional component in React js?

My challenge involves extracting data from an API by manipulating a URL. Specifically, I must retrieve a specific piece of information upon page load and then incorporate it into my URL before fetching the data. var genre_id; var genre; const MOVIE_URL = ` ...

Performing String formatting in JavaScript using an array

I've been utilizing the stringformat library to format strings in my node.js applications. var stringFormat = require('stringformat'); stringFormat.extendString(); In my current project, I'm attempting to pass an array of parameters a ...

Is Yarn 2.0's zero-install approach better suited for production or development deployments?

Our team is currently transitioning from yarn 1.x to yarn 2 (yarn 3.1.1) and I'm feeling a bit lost when it comes to configuring yarn in our CI/CD setup. Our current pipeline for deploying to our Kubernetes cluster looks like this: On Pull Request br ...

Mastering the art of implementing dynamic template variables in TinyMCE

After exploring the 'full' example and conducting research on the Wiki and moxie forums, I have yet to find a solution. I am attempting to implement what the wiki states is possible, but encountered an issue when replacing the 'staffid' ...

JavaScript: Transform an Array of Strings into an Array of Objects

Here is an array containing different strings: let myArray : ["AA","BB" , "CC" ...] My goal is to transform it into an array of objects: myArray = [{"id":1 , "value": "AAA"},{"id":2 , "value": "BBB"},{"id":3 , "value": "CCC"}...] I attempted to achiev ...