Search code examples
javascriptgoogle-mapsnext.jsaxioscors

Nextjs google places autocomplete giving incorrect values


I am trying to use google auto complete to get the names of mosques only in united kingdom, I am recieving data but its global and it is not for 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 im getting:

{
    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 is correct as it includes mosque but everything else is weird. The name of the mosque is not present and the data is from other countries


Solution

  • You are using parameters wrong, Here is the correct version:

    const response = await axios.get(apiUrl, {
          params: {
            input: input,
            key: apiKey,
            types: "mosque", 
            components: "country:uk", // Set the country to the UK
          },
        });