I’m working on a TypeScript application using VSCode that will display a Google Map.
I saw several ways of doing this and it confuses me, I would like to start on good basis.
First, I chose those options in my TSConfig.json
:
"module": "ESNext",
"target": "ES6",
"moduleResolution": "node",
"esModuleInterop": true,
"declaration": false,
"lib": ["ES6", "DOM"],
I saw that I could load Google Maps from the HTML page like this but I don’t like leaving the key in the HTML:
<script>
(g=>{var h,a,k,p="The Google Maps JavaScript API",c="google",....then(()=>d[l](f,...n))})({
key: "xxx",
v: "weekly",
});
</script>
Then I saw that I can also load it from TypeScript, I’d like to load dependencies only when required so I liked it but how does it compare to the previous method, is there one that will get deprecated, is there a prefered one in my scenario ?
private map: google.maps.Map | undefined = undefined;
public async init(): Promise<void> {
try {
await this.loadGoogleMapsApi().then(() => {
this.initMap();
});
} catch (error) {
console.error('Failed to load Google Maps API:', error);
}
}
private async loadGoogleMapsApi(): Promise<void> {
if (!(window as any).google || !(window as any).google.maps) {
const script = document.createElement('script');
script.src = `https://maps.googleapis.com/maps/api/js?key=xxx`;
script.defer = true;
script.async = true;
document.head.appendChild(script);
await new Promise<void>((resolve, reject) => {
script.onload = () => resolve();
script.onerror = () => reject(new Error('Failed to load the Google Maps API'));
});
}
}
private async initMap(): Promise<void> {
try {
const { Map } = await google.maps.importLibrary("maps") as google.maps.MapsLibrary;
//strangely after above line, code goes to game.init().finally block before hiting next line.
const pointA = new google.maps.LatLng(37.7749, -122.4194); // San Francisco
this.map = new Map(this.mapElement, {center: pointA, zoom: 6});
} catch (error) {
console.log(error);
}
}
Anyhow, when I run this, I have no error and a blank page.
If you could help with a good TypeScript startup page, it would help me a lot, thank you.