Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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".

like image 528
Marcel Avatar asked Aug 13 '17 15:08

Marcel


1 Answers

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.

like image 55
Lazar Ljubenović Avatar answered Oct 19 '22 23:10

Lazar Ljubenović