Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting google.maps.Map instance from @angular/google-maps

I need to get google.maps.Map. I cannot see official way in docs. But I see that whole component is exportedAs. But when I use it in template:

<google-map [center]="{lat: mapaLat, lng: mapaLng}"
                [zoom]="mapaZoom" [options]="{mapTypeControl: true}"
                #mapInstance="googleMap"></google-map>

it is local variable. How to get it in my component's typescript?

Or maybe there is other way to get google.maps.Map?

like image 794
piernik Avatar asked Aug 29 '26 13:08

piernik


2 Answers

as mentioned in the official documents, you can access map instance using ViewChild decorator and seems you already added it to the component HTML, you just need to define it in your wrapper component typescript like this:

 @ViewChild(GoogleMap) googleMap: GoogleMap;

and then use it, maybe you need to start using it after AfterViewInit get called to make sure the map component initilaized

like image 70
Ahmad Abu Saa Avatar answered Aug 31 '26 07:08

Ahmad Abu Saa


My use case was re-focusing the map once several markers were added and bounds were set.

Using @ViewChild didn't work for me, I had to use the mapInitialized event to get access to the map instance.

<google-map (mapInitialized)="onMapReady($event)" [center]="center" [zoom]="zoom" [options]="mapOptions"> ... </google-map>

  /**
   * Fit bounds and show all available markers after the map is fully loaded
   * @param {google.maps.Map} map : Google Map Instance
   */
  public onMapReady(map: google.maps.Map): void {
    
    map.fitBounds(this.bounds, 20);

  }
like image 39
Ioana Cucuruzan Avatar answered Aug 31 '26 07:08

Ioana Cucuruzan



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!