Search code examples
angulartypescriptgoogle-mapsgoogle-maps-api-3

How to show two maps in two different pages in an Angular SPA


I am trying to insert two Google Maps in two different pages in a single page application in Angular. When I open the first page I see the map correctly, when I go to the second the map is not visible. Same thing on the contrary, if I refresh the site and open the second page first I see the map correctly, if I then go to the first page I don't see the map. It is as if it only initializes the first map that is displayed and the second one does not.

Do you know how I can do to see two different maps on two different pages?

This is the code, in the index.html I put the google script at the bottom of the body.

<script src="https://maps.googleapis.com/maps/api/js?key=[KEY]=weekly" defer >

the first component ts:

export class ExploreComponent implements OnInit, AfterViewInit {
ngAfterViewInit(): void {
this.initMap();
}

map?: google.maps.Map;
infoWindow?: google.maps.InfoWindow;
initMap() {
const myLatLng = { lat: 45.902780, lng: 16.496370 };

    this.map = new google.maps.Map(
      document.getElementById("map") as HTMLElement,
      {
        zoom: 6,
        center: myLatLng,
        // disableDefaultUI:true,
        streetViewControl: false,
        fullscreenControl: false
      }
    );
    
    const locationButton = document.createElement("button");
    
     locationButton.textContent = "Pan to Current Location";
     locationButton.classList.add("custom-map-control-button");
    
    this.map.controls[google.maps.ControlPosition.RIGHT_BOTTOM].push(locationButton);
    
    locationButton.addEventListener("click", () => {
      this.getActualPosition();
    });
    
    this.getActualPosition();

};
}

The HTML of the first component:

<div id="map" style="width: 100%; height: 95%;"></div>

The second component ts is structured practically the same:

ngAfterViewInit(): void {
this.initMap();
}

map?: google.maps.Map;
initMap() {
const myLatLng = { lat: 41.902780, lng: 12.496370 };

    this.map = new google.maps.Map(
      document.getElementById("map") as HTMLElement,
      {
        zoom: 6,
        center: myLatLng,
      }
    );

}

HTML of the second component:

<div id="map" style="width: 100%; height: 250px; margin: auto; border-radius: 5px;margin-top: 5px;"\>\</div>

Solution

  • Whenever I run into this, it's because both map divs are present in the DOM at the same time. This would be the case if one map was in a sub-component of another, or if one of the maps was hidden instead of not present (e.g. if you use [hidden] instead of *ngIf).

    I would try changing the ID of the second map, to be something else, then of course remember to update your second map's constructor to use the new ID.