If you ever wondered how to add a Google map to you Angular app, I'm going to show you how. I know there are libraries to do so like AGM which works great but for more advanced use cases, I will suggest for you do it the way I will show you here. If you are looking for basic map functionality follow my other tutorial:
https://dev.to/devpato/setup-google-maps-with-agm-in-angular-app-33em
Note: this is the repo. branch part 1 has the final code for this tutorial
https://github.com/devpato/angular-google-maps-tutorial
1) Create a new Angular project:
ng new angular-gmap
2) Generate a Google Maps API key here
3) Inside of your project go to the index.html file and add the following line inside of your head tags:
<head>
.
.
<script src="https://maps.googleapis.com/maps/api/js?key=YOUR-API-KEY"
type="text/javascript"></script>
</head>
4) Now add your API Key inside of the script tag.
5) Type to add allow Angular to use the Google Maps types. In your terminal run:
npm i @types/googlemaps
6) Time to tell Angular we are ready to use the Google Maps Types. Open your tsconfig.app.json and tsconfig.spec.json and add googlemaps to the types array inside of the compilerOptions object.
Note: I only put it on the tsconfig.app.json file; some people have encountered issues and have to add it to both files mentioned above.
"compilerOptions": {
"outDir": "./out-tsc/app",
"types": ["googlemaps"]
},
7) Inside of your app.component.html add the following code:
<div #mapContainer id="map"></div>
8) Time to add some CSS to your map. Go to you app.component.css file and add the following:
#map {
height: 500px;
width: 100%;
}
Note: If you don't add the height, your map won't show in your app.
9) In your app.component.ts file your import line at the top of you file should look like this:
import { Component, AfterViewInit, ViewChild, ElementRef } from
'@angular/core';
10) Inside of the same file, we give the app access to the DOM element we have created with ViewChild
@ViewChild('mapContainer', {static: false}) gmap: ElementRef;
Where mapContainer is the name of the HTML element we previously created.
11) Now create a map variable that contains the Google Maps API inside of your app.component.ts.
map: google.maps.Map;
We are able to do this because of the google map types we added to the project.
12) In the app.component.ts file add the following variables:
lat = 40.730610;
lng = -73.935242;
13)Let's create a coordinates variable to use our latitude and longitude.
coordinates = new google.maps.LatLng(this.lat, this.lng);
14) In the same file, create a mapOptions variable as followed:
mapOptions: google.maps.MapOptions = {
center: this.coordinates,
zoom: 8,
};
15) Inside of your app.component.ts create a mapInitializer() function.
mapInitializer() {
this.map = new google.maps.Map(this.gmap.nativeElement,
this.mapOptions);
}
16) Time to use the AfterViewInit. Your file should look like this:
...
export class AppComponent implements AfterViewInit {
...
ngAfterViewInit() {
}
}
17) Inside of your ngAfterViewInit add the following line:
ngAfterViewInit() {
this.mapInitializer();
}
Time to add a Marker
18) Create a new variable
marker = new google.maps.Marker({
position: this.coordinates,
map: this.map,
});
19) Add the marker to the map by adding the following line to the mapInitializer() function:
this.marker.setMap(this.map);
20) Your app.component.ts should look like this:
export class AppComponent implements AfterViewInit {
title = 'angular-gmap';
@ViewChild('mapContainer', { static: false }) gmap: ElementRef;
map: google.maps.Map;
lat = 40.73061;
lng = -73.935242;
coordinates = new google.maps.LatLng(this.lat, this.lng);
mapOptions: google.maps.MapOptions = {
center: this.coordinates,
zoom: 8
};
marker = new google.maps.Marker({
position: this.coordinates,
map: this.map,
});
ngAfterViewInit() {
this.mapInitializer();
}
mapInitializer() {
this.map = new google.maps.Map(this.gmap.nativeElement,
this.mapOptions);
this.marker.setMap(this.map);
}
}
You should see something like this:
Don't forget to check the section part, to add multiple markers and info windows to the markers
https://dev.to/devpato/multiple-markers-on-google-map-in-angular-app-the-pro-way-pt2-50p0
The completed repo project:
https://github.com/devpato/angular-google-maps-tutorial
Top comments (37)
Hi! great Tutorial!
But I run ng test but it has an error ReferenceError: google is not defined
Not sure how to mock google api or in which way to resolve this. Any clue?
do you have a repo?
Have you tried steps 5 and 6?
Have you tried this?
TS error for the google declaration, that you should add to your tsconfig.app.json and tsconfig.spec.json this line "types": ["googlemaps"]
keep me posted
Hi Thanks for you reply. I had to mock the googlemap and I follow this github.com/ScottieR/angular-google...
and add in the karma file
files:[
"maps.googleapis.com/maps/api/js?ke...",
"src/app/test/google.api.mock.js"
],
so this solved your issue? correct?
yes!
cool! Thanks for sharing your solution
The same issue, cannot make it work even using different tricks and workarounds
do you have a repo?
Have you tried this? and step 5 and 6 from the article
TS error for the google declaration, that you should add to your tsconfig.app.json and tsconfig.spec.json this line "types": ["googlemaps"]
yes, I'd tried that but without success. I'd reproduced the issue in this simplified setup - small Angular app with a single module with google maps, addressing global google maps object inside the component code. The error when running Jest suite is the same.
Hi bud! did yo have a chance to add what Pamela did by adding the mock file? Let me know if it works. i took a look to your app. I noticed you are using the angular google maps. I tried so many things and I can't resolve your issue. If what Pamela did doesn't work for you let me know. I will ask my friends who are GDEs on Google Maps and some other GDEs on Angular
Wow, that's really a gem 🔥 I mean the idea Pamela mentioned. As I use Jest, I've changed it a little bit, so I use basically the same mock object but put it into
jest.config.js
(and use another config property, correspondingly)So Pato, thanks for getting into it, and big thanks to Pamela for providing this trick 👍
I am having the same error
Uncaught (in promise): ReferenceError: google is not defined.
Tried creating index.d.ts file and even spec.ts.config but not working.
Any solution please.
here my repo - find in mapComponent
github.com/13bhavya/ng-website.git
Read comments above. They contain the solution :)
did you try pamelas aproach?
I tried to understand that after I found there was an error in script of index.html :
<script src=”http://maps.googleapis.com/maps/api/js?key=API-KEY" type="text"></script>
I added only text not Javascript.
Such a silly I was finding everywhere else.
No need to create index.d.ts file.
Thanks though.
Im glad you found you issue :)
Thanks. This helped me to get rid of agmp, because that wouldn't allow me to customize the style.
You could also add the part that if you get a TS error for the
google
declaration, that you should add to yourtsconfig.app.json
andtsconfig.spec.json
this line"types": ["googlemaps"]
thanks!! i will add it :)
Hi, this is great thank you!
Worked with first trial - with some error messages.
I got an error: "ERROR in src/app/app.component.ts:11:8 - error TS2503: Cannot find namespace 'google'." when serving (though map rendered OK as such). Pamela's instructions did not help.
Instead I added a file "index.d.ts" to the ./src directory as instructed here: medium.com/@jkeung/integrating-goo... .The file only contains " declare module 'googlemaps'; ", and then serving again got rid of error message.
I have a repo at github.com/Helleeni/angular-gmap.git
PS. Tried this in a real project and only needed to add "index.d.ts" file with the above mentioned content to get rid of error messages. No other changes necessary (so far ...). Thanks again for great tutorials!
thanks for this! I will make a reference to this comment in the actual post pretty soon and give you credit ;)
Hey Pato,
Thanks a lot for the wonderful post and it works like a Gem..!!
I have a question though, is there any way to track the Lat and Lng information when the user clicks on different areas on the map.?
Thanks in advance..!! :)
Hey Pato,
Managed to find it. Did some tweaking on the code from Javascript Google API reference. :)
Once again, thanks for an excellent post..!! It was really helpful..!!
Hello,
The @types/googlemaps hasn't got
preventMapHitsAndGesturesFrom
method ofgoogle.maps.OverlayView
. Do you know how to make it available in type?Thank you.
I created github.com/DefinitelyTyped/Definit... issue .
I will check it out!
@Pato I created pull request adding those methods and waiting for reviewers.
github.com/DefinitelyTyped/Definit...
Hi, how to add event on click of marker want to open pop up. How can i do?
dev.to/devpato/multiple-markers-on...
Hi! I don't know why I just saw this. I'm about to work on that tutorial and post it soon ;)
Thanks! Worked first time :)
Great tutorial friend, do you give private lessons specifically on map events? I am interested in showing the current position on the map and several marker near the location but I do not get it
I can try to make a tutorial on that!
let me know if this can help you dev.to/devpato/multiple-markers-on...
By doing this, Secret Google API Key will always be visible to end-user, Is there is any way to hide the key and still use it?
If you add the security to your API key on the Google platform it won't matter who has your key. You can specify which website can only use your key