npm i @agm/core
Directory Structure
Now modify the app.module.ts
to register the package and replace your own api_key
from google cloud console
app.module.ts
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { AgmCoreModule } from '@agm/core'; import { AppComponent } from './app.component'; @NgModule({ declarations: [AppComponent], imports: [ BrowserModule, AgmCoreModule.forRoot({ apiKey: '' }) ], providers: [], bootstrap: [AppComponent] }) export class AppModule {} |
Now modify the template
file and copy below the following code
app.component.html
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
<h1>Angular Google Maps (AGM) Demo</h1> <p><a href="https://angular-maps.com/" target="_blank">Official Website</a></p> <agm-map [latitude]="lat" [longitude]="lng" [zoom]="zoom" [disableDefaultUI]="false" [zoomControl]="false" (mapClick)="mapClicked($event)"> <agm-marker *ngFor="let m of markers; let i = index" (markerClick)="clickedMarker(m.label, i)" [latitude]="m.lat" [longitude]="m.lng" [label]="m.label" [markerDraggable]="m.draggable" (dragEnd)="markerDragEnd(m, $event)"> <agm-info-window> <strong>InfoWindow content</strong> </agm-info-window> </agm-marker> </agm-map> |
Now you need to add the code inside the app.component.ts
file as shown below
app.component.ts
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 |
import { Component } from '@angular/core'; import { MouseEvent } from '@agm/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: [ './app.component.css' ] }) export class AppComponent { // google maps zoom level zoom: number = 8; // initial center position for the map lat: number = 51.673858; lng: number = 7.815982; clickedMarker(label: string, index: number) { console.log(`clicked the marker: ${label || index}`) } mapClicked($event: MouseEvent) { this.markers.push({ lat: $event.coords.lat, lng: $event.coords.lng, draggable: true }); } markerDragEnd(m: marker, $event: MouseEvent) { console.log('dragEnd', m, $event); } markers: marker[] = [ { lat: 51.673858, lng: 7.815982, label: 'A', draggable: true }, { lat: 51.373858, lng: 7.215982, label: 'B', draggable: false }, { lat: 51.723858, lng: 7.895982, label: 'C', draggable: true } ] } // just an interface for type safety. interface marker { lat: number; lng: number; label?: string; draggable: boolean; } |
Now add the css
code inside the app.component.css
file as shown below
app.component.css
1 2 3 |
agm-map { height: 100vh; } |
Running the App
Now to run the app we can start the angular
app as shown below
ng serve
FULL SOURCE CODE