Getting google.maps.Map instance from @angular/google-maps
Asked Answered
A

3

6

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?

Allin answered 7/10, 2021 at 8:44 Comment(0)
H
7

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

Hovey answered 7/10, 2021 at 9:3 Comment(0)
R
7

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);

  }
Rintoul answered 29/1, 2022 at 23:44 Comment(2)
Thanks for posting the alternative approach. Waiting on the map initialization and then calculating the bounds as southwest and northeast google.maps.LatLng instances building a google.maps.LatLngBounds object to pass into the fitBounds method worked extremely well.Gnostic
Can you please help on this: #78075503Ruminate
U
0

Try to use ngAfterViewInit() hook, because map instance not available before it.

Undone answered 31/8, 2022 at 8:54 Comment(1)
Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.Apfelstadt

© 2022 - 2024 — McMap. All rights reserved.