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

Display content in a div after the page is fully loaded with either a placeholder or animated loading

Hello everyone, this is my first post on here. I am relatively new to PHP, so any help or advice would be greatly appreciated. ...

What could be causing my Angular to malfunction?

I've encountered some challenges while trying to run angular on my computer. I have been studying angular through demos on w3 schools that showcase various components. Currently, I am experimenting with this one: http://www.w3schools.com/angular/try ...

The code functions properly on a standalone device, however, it encounters issues when

I am facing an issue with my JavaScript code. It works perfectly fine when I run it on my local machine, but once I upload it to the server, it only functions properly after I refresh the page. Below is the code in question. Please do not hesitate to rea ...

Include image hover text without using HTML

I am looking to add a hover effect to some images using CSS and JS since I cannot directly edit the HTML file. The goal is to have centered text pop out when hovering over certain images. I know the div class of the image but unfortunately, I cannot add te ...

Node.js promises are often throwing Unhandled Promise Rejection errors, but it appears that they are being managed correctly

Despite my efforts to handle all cases, I am encountering an UNhandledPromiseRejection error in my code. The issue seems to arise in the flow from profileRoutes to Controller to Utils. Within profileRoutes.js router.get('/:username', async (r, s ...

Using React and Typescript, implement an Ant Design Table that includes a Dropdown column. This column should pass

Next Row: { title: "Adventure", render: (item: ToDoItem) => { //<- this item return ( <Dropdown overlay={menu}> <Button> Explore <DownOutlined /> </Button> </Dropdown&g ...

Managing registration with an existing email address in Supabase

Currently, I am working on implementing a sign-up functionality using Supabase and I want to be able to inform the user if they try to sign up with an email that already exists in the system. However, I am facing a challenge in identifying this particular ...

Exploring the concept of union return types in TypeScript

Hello, I am facing an issue while trying to incorporate TypeScript in a way that may not be its intended use. I have created a custom hook called useGet in React which can return one of the following types: type Response<T> = [T, false, false] | [nul ...

Encountered a TypeError in React 16.7: The function (0, _react.useState) is not recognized

Error: TypeError: (0 , _react.useState) is not a function React versions currently being used: "react": "^16.7", "react-dom": "^16.7", File src/App.js: import {memo, useState} from 'react' export default memo(() => { useS ...

Changing environment variables for jasmine tests

My Angular service code snippet includes importing the environment like this: import {environment} from '../environment' .... public something() { if(environment.production) { // do stuf } else { // do something else } } I am now l ...

Typed NextJs navigation to a specific route

<Link href="/about"> <a>About Us</a> </Link> Is there a way to ensure type safety with NextJs links? Currently, it is challenging to restructure the Link component as it is just a string. I stumbled upon this repos ...

Exploring the power of event triggers in Next.js for a serverless architecture

Exploring the world of serverless computing, I've come across the issue of cold start time. Every time a user inputs a new value, it triggers an API call to generate suggestions that need to be returned promptly. However, with the potential del ...

JavaScript code is failing to render data properly within HTML documents

I am facing an issue while trying to display data extracted from JSON in HTML. Despite my efforts, the data is not showing up on the webpage. I am unsure about what might be causing this error. Any assistance in resolving this matter would be greatly appre ...

The Next.js app's API router has the ability to parse the incoming request body for post requests, however, it does not have the

In the process of developing an API using the next.js app router, I encountered an issue. Specifically, I was successful in parsing the data with const res = await request.json() when the HTTP request type was set to post. However, I am facing difficulties ...

Issue encountered while retrieving information from XML file through AJAX

I am facing an issue while using AJAX to fetch data from an external XML file. The error I receive is "Invalid argument" and I am working with IE 8. Below is the code snippet: var xhr; xhr = new XMLHttpRequest(); xhr.open("GET","C:/Users/abc/Desktop/Pr ...

Utilizing Nuxt Axios to assign response data to a variable will dynamically modify the content of the

async fetch() { try { console.log(await this.$api.events.all(-1, false)); // <-- Logging the first statement const response = await this.$api.events.all(-1, false); // <-- Assigning the result console.log(response); // <-- Lo ...

When the form is submitted, any blank inputs and their corresponding hidden fields will be disabled

I created a form that has multiple input fields, and users have the option to enter values or leave them blank. Each input field is accompanied by a hidden input field which contains a specific id unique to the corresponding visible input field. To disable ...

Using two distinct buttons to submit information using various methods

When button 1 is clicked, I want it to update the row. When button 2 is clicked, I want it to create another row. This is the controller code for updating: public function update(Request $request, $id){ $pay = Payroll::find($id); $pay ->idnumb ...

What is the most effective way to create a live preview using AngularJS and CSS?

Is there a way to dynamically change the background color of the body based on the hexadecimal value entered in a textfield, without using jQuery? I want the change to happen live as the user types. The current code works but it doesn't feel right. I ...

Need to capture click events on an HTML element? Here's how!

I am attempting to capture click events on an <object/> element that is embedding a Flash file This is the approach I have taken so far: <div class="myban" data-go="http://google.com"> <object class="myban" data="index.swf>">< ...