Issues with location forecasts and .getPlace() when utilizing the Google Maps loader for Place Autocomplete in Vue are causing functionality problems

After setting up a Vue 2 app using the vue cli, I noticed that when typing an address, no suggestions were populating from the dropdown. Checking the network tab, I observed the

AutocompletionService.GetPredictions
call triggering without any errors upon page loading. https://i.sstatic.net/q4hpa.png

In response to my previous inquiry on Stack Overflow, I was advised to utilize the google maps loader,npm, which I promptly implemented.

<template>
  <div id="app">
    <img alt="Vue logo" src="./assets/logo.png" />
    <input
      id="detailedLocation"
      ref="autocomplete"
      type="text"
      v-model="address"
      @input="locatorInfo"
    />
    <ul>
      <li v-for="(result, i) in searchResults" :key="i">
        {{ result }} // list of all places
      </li>
    </ul>
  </div>
</template>

<script>
import { Loader } from "@googlemaps/js-api-loader";
const loader = new Loader({
  apiKey: "AIzaSyCcm...........",
  version: "weekly",
  libraries: ["places", "map"],
});

export default {
  name: "App",
  data() {
    return {
      info: null,
      searchResults: [],
      address: "",
    };
  },
  async mounted() {
    let location;
    const center = { lat: 40.84498856765032, lng: -73.71060855293794 };
    // Create a bounding box with sides ~10km away from the center point
    const defaultBounds = {
      north: center.lat + 0.1,
      south: center.lat - 0.1,
      east: center.lng + 0.1,
      west: center.lng - 0.1,
    };
    const input = document.getElementById("detailedLocation");
    const options = {
      types: ["address"], // the error was type: cities
      bounds: defaultBounds,
      fields: ["place_id", "geometry", "name", "address_components"],
    };
    loader
      .load()
      .then((google) => {
        location = new google.maps.places.Autocomplete(input, options);

        location.addListener(
          // document.getElementById("detailedLocation"),
          "place_changed",
          onPlaceChanged
        );
        console.log(location);
      })
      .catch((e) => {
        console.log(e);
        // do something
      });
    const onPlaceChanged = () => {
      const place = location.getPlace();
      console.log(location, place, "LINE 79");

      if (!place.geometry) {
        document.getElementById("detailedLocation").placeholder =
          "Enter a place";
      } else {
        document.getElementById("detailedLocation").innerHTML =
          place.formatted_address;
        console.log(place.formatted_address, "line 60");
      }
    };
  },
  methods: {
    locatorInfo() {
      if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition((position) => {
          console.log(position.coords.latitude, position.coords.longitude);
        });
      }
    },
    printData() {
      this.displaySuggestions();
      console.log(this.$refs["autocomplete"].value);
    },
    displaySuggestions(predictions, status) {
      if (status !== window.google.maps.places.PlacesServiceStatus.OK) {
        this.searchResults = [];
        return;
      }
      this.searchResults = predictions.map(
        (prediction) => prediction.description
      );
    },
  },
};
</script>

Upon entering and submitting an address, there were no errors detected. Uncertain of what might be going wrong, I revisited the google developers video on google places autocomplete widget, and thoroughly reviewed the documentation on AutocompleteService Class. The network call points to AutocompleteService instead of just Autocomplete, as it would for a widget. Despite initializing the loader's constructor for Autocomplete, the issue persists. What could be causing this discrepancy? How can I troubleshoot and resolve this?

EDIT

I have provided a CodeSandbox link and made modifications to the code by changing the definition of onPlaceChanged to an anonymous function, aligning with the example in the docs, docs example

Answer №1

After troubleshooting, I realized that the issue was with the options object. Instead of specifying type: cities, it should have been type: address (for my specific needs). Utilizing @googlemaps/js-api-loader proved to be a successful alternative to manually adding the script tag in index.html. For future reference, one can also opt to use an anonymous function as demonstrated in the autocomplete documentation example. It's important to watch out for small typos like typing 'AutoComplete' instead of the correct spelling, 'Autocomplete'. Though the documentation for the api loader is lacking, this example should still help you get started.

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

Observing changes to attributes in AngularJS is a useful feature that allows for

I am looking to update the attribute of an element by using its id and have the element respond to this change. After trying to showcase my situation in a plunkr, I encountered issues with even getting ng-click to function properly. My goal is to invoke ...

Having trouble with the "next" pagination button not loading cards, even though the numbered buttons are working perfectly

My pagination numbers are functioning correctly, but I'm having trouble with my "next" or "previous" buttons. I am using Bootstrap 5 and jQuery to load cards from an array. The issue seems to be with the currentPage variable in my displayList function ...

Unable to adjust the padding of a div while the Bootstrap 4 navbar is in a collapsed state on mobile devices

I am facing an issue with a fixed navbar at the top of my page. Below the navbar, I have the page content which includes a Bootstrap 4 image carousel. The problem arises on mobile devices where I need to add top-padding to the page-container (below the nav ...

Customizing Your JQuery.awesomeCloud.plugin with a Tooltip Functionality using jQuery

Is it possible to integrate a jQuery Tooltip feature when hovering over specific words in a word cloud? I am currently using [jQuery.awesomeCloud.plugin]:https://github.com/indyarmy/jQuery.awesomeCloud.plugin If there is an alternative method to add toolt ...

Encountering NPM install gyp errors in VSCode indicating that gyp is searching for Visual Studio

Running npm install on a local project has been quite challenging for me, as I keep encountering errors every time I try. Fortunately, some valuable information I found related to gyp and Python helped me make some progress. However, I'm currently fac ...

What is the best method for retrieving a local value in Javascript?

Consider a scenario where there exists a variable named animationComplete (which is part of a 3rd-party library) and a function called happenAfterAnimation: An easy solution would involve the following code snippet: while(!animationComplete) { // Do n ...

Capture each touchdown and convert it to currency format

As a novice in the field of JS, I have put in a lot of effort into learning from various sources such as websites, documentation, friends, and other questions on Stack Overflow. However, despite all my efforts, I seem to be stuck at this point. $(docume ...

Calculating with nested arrays in Vue.jscomputed functions

After coming from a background using Knockout.js, I am considering exploring Vue.js for my upcoming projects. One aspect that has confused me is implementing computed functions on nested arrays of data. Imagine we retrieve this data structure from an ajax ...

Within the ASP.NET Framework 4, it is necessary to enable the Listbox control to trigger an event when a user double

Currently, I am developing a project in ASP.NET 4. I have encountered a situation where the regular ListBox in version 4.5 includes an attribute named OnMouseDoubleClick. However, since I am using ASP.Net 4, I am looking for the best approach to replicat ...

Reduce and combine JavaScript files without the need for Grunt or Gulp

My project involves working with over 50 JavaScript files that I want to combine and compress to optimize file size and minimize HTTP requests. The catch is, the client's system does not have Node or npm installed. How can I accomplish this task witho ...

classes_1.Individual is not a callable

I am facing some difficulties with imports and exports in my self-made TypeScript project. Within the "classes" folder, I have individual files for each class that export them. To simplify usage in code, I created an "index.ts" file that imports all class ...

Executing multiple AJAX calls at the same time in PHP

I have a puzzling question that I can't seem to easily solve the behavior of this situation There are two ajax call functions in my code: execCommand() : used for executing shell commands through PHP shell_exec('ping 127.0.0.1 > ../var/l ...

Transfer Data from a Factory to a Controller in AngularJS

Although it may seem like a simple question, it has taken me nearly 3 hours to try and figure out what went wrong here. Perhaps someone could help identify the issue and provide a solution (it seems like an easy fix, but I'm just not seeing it). So, h ...

showcasing a map on an HTML webpage

Seeking advice on integrating a map feature in HTML to mark store locations. Working on an app for a business community and need help with this specific functionality. Your assistance would be greatly appreciated! ...

When submitting a form with the jQueryForm plugin, take action on the form by selecting it with `$(this)`

I have a situation where I have multiple forms on one page and am utilizing the jQuery Form plugin to manage them without having to reload the entire page. The issue arises when I need some sort of visual feedback to indicate whether the form submission wa ...

React Redux Loading progress bar for seamless navigation within React Router

Currently, I am working on adding a loading bar similar to the one used by Github. My goal is to have it start loading when a user clicks on another page and finish once the page has fully loaded. In order to achieve this, I am utilizing material-ui and t ...

Guide to setting up a datePicker in a cellEditorSelector

In my grid, I want to have different editors for different rows within the same column. The ag-Grid documentation provides information on how to achieve this using colDef.cellEditorSelector as a function: link I have successfully created unique editors fo ...

What is the process for including an additional button in the DateTimePicker feature of material UI?

I'm currently utilizing DateTimePicker in my React application. https://i.sstatic.net/ShyTE.png I wish to incorporate a Clear button positioned to the left of the Cancel Button. import { MuiPickersUtilsProvider, DateTimePicker } from "@material-ui/ ...

Unable to update content within the `style` attribute when the HTML is stored in a variable

I am attempting to make changes to the style html - specifically by replacing a string, but unfortunately it is not functioning as expected. I am struggling to obtain the final updated html. Below is my attempt: var html = "<style>043BF83A8FB24A418 ...

Creating static files using relative paths in Nuxt

Is there a way to customize the file paths when generating static files using yarn run generate? For instance, I am trying to achieve <img src="images/image.png"> instead of the default <img src="/image/image.png>. I attempted to modify the co ...