Biffidus
Biffidus

Reputation: 13

'google' is not defined on Vue.Js project with Google Maps

I'm trying to create a google maps box without third party libraries on a Vue.js project working with typescript, but I'm having some headaches. In practice I ran the command from the official site https://developers.google.com/maps/documentation/javascript/using-typescript "npm i -D @ types / google.maps", and I entered the code below but the problem "'google' is not defined" occurs. I don't know what the problem could be.

Here the code

export default {
  mounted: function () {
    let map: google.maps.Map;
    const center: google.maps.LatLngLiteral = { lat: 30, lng: -110 };

    function initMap(): void {
      map = new google.maps.Map(document.getElementById("map") as HTMLElement, {
        center,
        zoom: 8,
      });
    }
  },
};

Upvotes: 1

Views: 2151

Answers (2)

Justin Poehnelt
Justin Poehnelt

Reputation: 3459

There are @types/google.maps and then there is the actual API which needs to be loaded.

import { Loader } from '@googlemaps/js-api-loader';

mounted: function () {
    const loader = new Loader({
      apiKey: "",
      version: "weekly",
      libraries: ["places"]
    });

    let map: google.maps.Map;
    const center: google.maps.LatLngLiteral = { lat: 30, lng: -110 };

    loader.load().then(() => { map = new 
       google.maps.Map(document.getElementById("map") as HTMLElement, {
        center,
        zoom: 8,
        });
     });
    
  },

Upvotes: 1

fditz
fditz

Reputation: 882

It seems that the way you've used (and what is written in the google site) is if your project is pure typescript.

Since you are dealing with Vue I would recommend using the following library: https://vue3-google-map.netlify.app/getting-started/#your-first-map

They have an example of usage there and I think you will have a better experience using it with Vue3 than trying to make it work. (You can probably remove the google stuff you currently have installed in your package.json)

Upvotes: 0

Related Questions