I\'d like to create a google map component that work like that : https://jsfiddle.net/gvvy5vxz/2/
It\'s based on this : https://developers.google.com/maps/documentat
As my code loads google maps API asynchronously, the above answers did not work for me. My problem was typescript use google variable before loaded google API.
Here is a solution I found.
To see async map loader code, see Load Google Maps JS API in component [Angular]
service
//map.service.ts
import { Injectable } from '@angular/core';
...
declare var google;
export let MyOverlay; // declare and use this from other ts file
@Injectable({ providedIn: 'root' })
export class MapService {
private static promise;
map: any;
public static load() {
if (!MapService.promise) {
MapService.promise = new Promise((resolve) => {
//load google api asynchronously
});
}
return MapService.promise;
}
async initMap(gmapElement, lat = -33.92, lng = 151.25) {
return MapService.load()
.then((gapi) => {
//map init
this.map = new google.maps.Map(gmapElement.nativeElement, {
//map options
})
/*** before init MyOverlay,
1. Google API should be loaded
2. AFTER MAP init(rendering), Overlay Object has Projection to calculate Overlay location
***/
this.initMyOverlay()
})
.catch(console.log)
}
initMyOverlay(){
class MyOverlayCls extends google.maps.OverlayView {
//omitted for code readability
}
MyOverlay = MyOverlayCls ; //assign class to variable
}
}
component
//map.component.ts
import { MapService, MyOverlay} from 'map.service';
...
@ViewChild('gmap') gmapElement: any
...
ngOnInit() {
console.log("maps init")
this.mapSvc.initMap(this.gmapElement).then(_ => {
//At this time, google API has been loaded and assigned MyOverlay as MyOverlayCls
let overlay= new MyOverlay(...)
})