6

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 2

1

It breaks because initMap function is not available when Google's script tries to call it. It's also not globally available as Google' script expects (it's scoped to the class).

There's an existing library called Angular Google Maps whose purpose is using Google Maps with Angular applications.

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

1 Comment

I understood that AGM was primarily for simple use cases and for more difficult application that installing the javascript version was prefered ??
0

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

Comments

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.