Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

google maps with typescript

I'm trying to include google maps javascript API into a project using Typescript and keep getting the error "Cannot find namespace 'google'.ts(2503)"

I am following the official documentation (https://developers.google.com/maps/documentation/javascript/load-maps-js-api) and have used "Use Dynamic Library Import" method to include the script tag in my html file. I am using parcel to convert the .ts file into .js and start a local server. If at this stage I open the chrome browser console and type "google" then it is accessible.

For the next step, in my .ts file I included the code from the official docs:

let map: google.maps.Map; // Cannot find namespace 'google'.ts(2503)

async function initMap(): Promise<void> {
  const { Map } = await google.maps.importLibrary("maps") as google.maps.MapsLibrary;
  map = new Map(document.getElementById("map") as HTMLElement, {
    center: { lat: -34.397, lng: 150.644 },
    zoom: 8,
  });
}

initMap();

In the official docs, uder the Typescript section (https://developers.google.com/maps/documentation/javascript/using-typescript), it says that "types are automatically generated" but I still explicitly download the type definitions using "npm i -D @types/google.maps" but still get an error.

If it helps, I have install Typescript and parcel globally.

like image 422
falah mahmood Avatar asked Dec 12 '25 16:12

falah mahmood


1 Answers

For everyone who is facing an error with the updated google maps javascript api, who simply need to follow the instructions from the official docs and remember to add /// <reference types="@types/google.maps" /> EXACTLY AS IS as the first line in your typescript file where you're initializing the map. Now the google namespace error will be gone.

Kindly, go through my comments above if you're facing other issues. I've mentioned a few of the errors/issues I had to face and have also provided solutions for them.

like image 114
falah mahmood Avatar answered Dec 14 '25 09:12

falah mahmood



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!