Home > OS >  Google Places Autocomplete API error, "google is not defined"
Google Places Autocomplete API error, "google is not defined"

Time:12-15

I am scaffolding a simple prototype using google places and maps api using Vue.

In index.html, I added the script tag, libraries, and api key, I get 200 response in the network tab.

        <script src="https://maps.googleapis.com/maps/api/js?key=My-api-key&libraries=places" async defer></script>

In App.vue, I added the following

 <input ref="autocomplete" type="text" />
 ...
<script>
  export default {
  name: "App",
  data() {
   return {
     autocomplete: "",
    };
  },
  methods: {},
  mounted() {
    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 originAutoComplete = google.maps.places.AutoComplete(
    this.$refs["autocomplete"],
   {
     bounds: defaultBounds,
   }
 );
 originAutoComplete.addListener("place_changed", () => {
   console.log(originAutoComplete.getPlace());
 });

enter image description here

How do I resolve this error? Is there a way to initialize this in App.vue script tag? The example google developers youtube works great, but I'd like to implement this in a Vue context. One other note, I tried adding window before the .google, no dice.

UPDATE 1

as per your advice, I installed googlemaps api loader and in App.vue:

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

     export default {
      name: "App",
      data() {
        return {
        autocomplete: "",
      };
    },
    methods: {
      printData() {
        console.log(this.$refs["autocomplete"].value);
     },
   },
    async mounted() {
      let origin;
      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,
      };
     loader
      .load()
       .then((google) => {
        origin = new google.maps.places.Autocomplete(
          this.$refs["autocomplete"],
          {
            types: ["cities"],
            defaultBounds,
            fields: ["place_id", "geometry", "name"],
          }
        );
        origin.addListener("place_changed", () => {
        console.log(origin.getPlace());
       });
      })
       .catch((e) => {
         console.log(e);
       // do something
     });

Now this issue is the drop down of selections is not appearing.

CodePudding user response:

The issue is that your Vue App JS is loading before the google maps JS. There are some options:

  1. Block your app loading on Google Maps by removing the async and defer from the script. Make sure the script tag is above your Vue JS after removing the async/defer.
  2. Incorporate a callback parameter or just check for existence of window.google in your vue component and allow vue to update when it is available.
  3. Use @googlemaps/js-api-loader in the Vue component. See Is `async/await` available in Vue.js `mounted`? for ways to incorporate.

I recommend option 3.

  • Related