How to implement Google Maps API (initMap) in Angular 4?

Viewed 4439

I try to integrate Google Maps in Angular.

index.html

<script async defer src="https://maps.googleapis.com/maps/api/js?key=api_key&callback=initMap"></script>

example.component.html

...
<div id="map"></div>
...

example.component.ts

...
ngAfterViewInit() {
        function initMap() {
            var uluru = {lat: -25.363, lng: 131.044};
            var map = new google.maps.Map(document.getElementById('map'), {
                zoom: 4,
                center: uluru
            });
            var marker = new google.maps.Marker({
                position: uluru,
                map: map
            });
        }
    }

I got still the error "initMap is not a function".

2 Answers

After looking arround for other solutions I ended up using Angular Google Maps npm module

Using these steps it help me to get started - https://angular-maps.com/guides/getting-started/ - map is showing perfect.

Steps:

npm install @agm/core

In the app.module.ts add this:

import { AgmCoreModule } from '@agm/core'

//on imports section
AgmCoreModule.forRoot({
  apiKey: 'YOUR_Maps_JavaScript_API_KEY_HERE'
})

In the component (.ts) that you want to show the map do this :

lat : number;
lng : number;

ngOnInit() {
    this.prepareMap() ;
}

prepareMap() {
    this.lat = 51.678418;
    this.lng = 7.809007;

    console.log("prepareDivMap finished");
}

in the corresponding .css file add this:

agm-map {
    height: 300px;
}

in the corresponding html part add this:

<agm-map [latitude]="lat" [longitude]="lng">
    <agm-marker [latitude]="lat" [longitude]="lng"></agm-marker>
</agm-map>

An here is the result of google maps embedded into a angular component using agm

enter image description here

Related