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?

3 Answers 3

9

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

Sign up to request clarification or add additional context in comments.

Comments

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

  }

2 Comments

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.
Can you please help on this: stackoverflow.com/questions/78075003/…
0

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

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.