DEV Community

Cover image for Setup Google Map In Angular App (The Pro Way) Part 1
Pato
Pato

Posted on • Updated on

Setup Google Map In Angular App (The Pro Way) Part 1

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
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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"]
   },
Enter fullscreen mode Exit fullscreen mode

7) Inside of your app.component.html add the following code:

    <div #mapContainer id="map"></div>
Enter fullscreen mode Exit fullscreen mode

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%;
   }
Enter fullscreen mode Exit fullscreen mode

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';
Enter fullscreen mode Exit fullscreen mode

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;
Enter fullscreen mode Exit fullscreen mode

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;
Enter fullscreen mode Exit fullscreen mode

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;
Enter fullscreen mode Exit fullscreen mode

13)Let's create a coordinates variable to use our latitude and longitude.

   coordinates = new google.maps.LatLng(this.lat, this.lng);
Enter fullscreen mode Exit fullscreen mode

14) In the same file, create a mapOptions variable as followed:

   mapOptions: google.maps.MapOptions = {
      center: this.coordinates,
      zoom: 8,
    };
Enter fullscreen mode Exit fullscreen mode

15) Inside of your app.component.ts create a mapInitializer() function.

   mapInitializer() {
    this.map = new google.maps.Map(this.gmap.nativeElement, 
    this.mapOptions);
   }
Enter fullscreen mode Exit fullscreen mode

16) Time to use the AfterViewInit. Your file should look like this:

   ...
   export class AppComponent implements AfterViewInit {
    ...
    ngAfterViewInit() {

    }
   } 
Enter fullscreen mode Exit fullscreen mode

17) Inside of your ngAfterViewInit add the following line:

   ngAfterViewInit() {
    this.mapInitializer();
   }
Enter fullscreen mode Exit fullscreen mode

Time to add a Marker

18) Create a new variable

    marker = new google.maps.Marker({
     position: this.coordinates,
     map: this.map,
   });
Enter fullscreen mode Exit fullscreen mode

19) Add the marker to the map by adding the following line to the mapInitializer() function:

   this.marker.setMap(this.map);
Enter fullscreen mode Exit fullscreen mode

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);
    }
   }
Enter fullscreen mode Exit fullscreen mode

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)

Collapse
 
pam81 profile image
Pamela

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?

Collapse
 
devpato profile image
Pato • Edited

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

Collapse
 
pam81 profile image
Pamela

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"
],

Thread Thread
 
devpato profile image
Pato

so this solved your issue? correct?

Thread Thread
 
pam81 profile image
Pamela

yes!

Thread Thread
 
devpato profile image
Pato

cool! Thanks for sharing your solution

Collapse
 
fyodorio profile image
Fyodor

The same issue, cannot make it work even using different tricks and workarounds

Collapse
 
devpato profile image
Pato

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

Thread Thread
 
fyodorio profile image
Fyodor

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.

Thread Thread
 
devpato profile image
Pato

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

Thread Thread
 
fyodorio profile image
Fyodor

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 👍

Collapse
 
13bhavya profile image
Bhavya Shah • Edited

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

Collapse
 
devpato profile image
Pato

Read comments above. They contain the solution :)

Collapse
 
devpato profile image
Pato

did you try pamelas aproach?

Collapse
 
13bhavya profile image
Bhavya Shah

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.

Thread Thread
 
devpato profile image
Pato

Im glad you found you issue :)

Collapse
 
radu_anastase profile image
Radu Anastase

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 your tsconfig.app.json and tsconfig.spec.json this line "types": ["googlemaps"]

Collapse
 
devpato profile image
Pato

thanks!! i will add it :)

Collapse
 
helleeni profile image
Helleeni • Edited

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!

Collapse
 
devpato profile image
Pato

thanks for this! I will make a reference to this comment in the actual post pretty soon and give you credit ;)

Collapse
 
jitheshmenon profile image
Jithesh Menon

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..!! :)

Collapse
 
jitheshmenon profile image
Jithesh Menon

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

Collapse
 
batorshikh profile image
Bat-Orshikh

Hello,

The @types/googlemaps hasn't got preventMapHitsAndGesturesFrom method of google.maps.OverlayView. Do you know how to make it available in type?

Thank you.

Collapse
 
batorshikh profile image
Bat-Orshikh
Collapse
 
devpato profile image
Pato

I will check it out!

Thread Thread
 
batorshikh profile image
Bat-Orshikh

@Pato I created pull request adding those methods and waiting for reviewers.
github.com/DefinitelyTyped/Definit...

Collapse
 
sandeep23948918 profile image
sandeep mishra

Hi, how to add event on click of marker want to open pop up. How can i do?

Collapse
 
devpato profile image
Pato
Collapse
 
devpato profile image
Pato

Hi! I don't know why I just saw this. I'm about to work on that tutorial and post it soon ;)

Collapse
 
brendanwilding profile image
brendanwilding

Thanks! Worked first time :)

Collapse
 
cristiansneydersilva profile image
CristianSneyderSilva

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

Collapse
 
devpato profile image
Pato

I can try to make a tutorial on that!

Collapse
 
devpato profile image
Pato

let me know if this can help you dev.to/devpato/multiple-markers-on...

Collapse
 
abhiipure1289 profile image
Abhishek Bhardwaj

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?

Collapse
 
devpato profile image
Pato

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

Collapse
 
eduardovrocha profile image
Eduardo V. Rocha

Great job man ! I wonder if this tutorial is for the static map?

Collapse
 
steve_torres_275913ef29a5 profile image
Steve Torres • Edited

I followed the tutorial. Works as expected with static data. How can I modify it as I am getting the coordinates from a REST API?
Also, sometimes I am getting a gray overlay over the map