Google Map In Angular

Agenda

  • What is Google Map
  • What is the Use
  • How to Implement GMap in Angular application

Google Map in Angular

Introduction

In this blog, we are going to learn how to implement Google Map(GMap) in angular applications with the help of the NgPrime library.

What is Google Map

Based on Wikipedia, Google Maps is a web mapping platform and consumer application offered by Google. It offers satellite imagery, aerial photography, street maps, 360° interactive panoramic views of streets, real-time traffic conditions, and route planning for traveling by foot, car, air, and public transportation.

What is the Use

Using a Google Map you can easily represent your site OR Locations.

GMap Implementation in Angular application

Step 1

Go to Angular application and install PrimeNg using the below command.

npm install primeng
npm install primeicons 

Step 2

Open angular.json file and add below styles,

"node_modules/primeng/resources/themes/saga-blue/theme.css",
"node_modules/primeng/resources/primeng.min.css",
"node_modules/primeicons/primeicons.css",

Google Map in Angular

Step 3

Open <Module Name>module.ts and import the below modules from PrimeNg.

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { GoogleMapComponent } from './google-map/google-map.component';

import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { GMapModule } from 'primeng/gmap';
import { ToastModule } from 'primeng/toast';
import { DialogModule } from 'primeng/dialog';
import { ButtonModule } from 'primeng/button';
import { CheckboxModule } from 'primeng/checkbox';

import { MessageService } from 'primeng/api';
import { FormsModule } from '@angular/forms';

@NgModule({
  declarations: [
    AppComponent,
    GoogleMapComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    BrowserAnimationsModule,
    GMapModule,
    DialogModule,
    FormsModule,
    ButtonModule,
    ToastModule,
    CheckboxModule
  ],
  providers: [MessageService],
  bootstrap: [AppComponent]
})
export class AppModule { }

Step 4

Open index.html file and add below script,

<script type="text/javascript" src="https://maps.google.com/maps/api/js?key=GoogleMapKey"></script> 

Note
GoogleMapKey Replaced with your Google map key.

If you don't have a key then use,

<script type="text/javascript" src="https://maps.google.com/maps/api/js?sensor=false"></script>

Step 5

Open <Component Name>.component.HTML and add below HTML,

<p-toast [style]="{marginTop: '80px'}"></p-toast>
<p-gmap #gmap [style]="{'width':'100%','height':'320px', 'margin-bottom': '1em'}" [options]="options"
    [overlays]="overlays" (onMapClick)="handleMapClick($event)" (onOverlayClick)="handleOverlayClick($event)"
    (onOverlayDragEnd)="handleDragEnd($event)"></p-gmap>
<button type="button" pButton label="Clear" icon="pi pi-times" (click)="clear()" style="margin-right:.25em"></button>
<button type="button" pButton label="Zoom In" icon="pi pi-plus" (click)="zoomIn(gmap.getMap())"
    style="margin-right:.25em"></button>
<button type="button" pButton label="Zoom Out" icon="pi pi-minus" (click)="zoomOut(gmap.getMap())"></button>
<p-dialog showEffect="fade" [(visible)]="dialogVisible" header="New Location" [style]="{width: '300px'}">
    <div class="p-grid p-fluid" *ngIf="selectedPosition">
        <div class="p-col-2"><label for="title">Label</label></div>
        <div class="p-col-10"><input type="text" autocomplete="off" pInputText id="title" [(ngModel)]="markerTitle">
        </div>
        <div class="p-col-2"><label for="lat">Lat</label></div>
        <div class="p-col-10"><input id="lat" type="text" readonly pInputText [ngModel]="selectedPosition.lat()"></div>
        <div class="p-col-2"><label for="lng">Lng</label></div>
        <div class="p-col-10"><input id="lng" type="text" readonly pInputText [ngModel]="selectedPosition.lng()"></div>
        <div class="p-col-2"><label for="drg">Drag</label></div>
        <div class="p-col-10">
            <p-checkbox [(ngModel)]="draggable" [style]="{'margin-top':'.25em'}"></p-checkbox>
        </div>
    </div>
    <ng-template pTemplate="footer">
        <div>
            <button type="button" pButton label="Add Marker" icon="pi-plus" (click)="addMarker()"></button>
        </div>
    </ng-template>
</p-dialog>

Step 6

Open <Component Name>.component.ts and add below code,
import { Component, OnInit } from '@angular/core';
import { MessageService } from 'primeng/api';
declare var google: any

@Component({
  selector: 'app-google-map',
  templateUrl: './google-map.component.html',
  styleUrls: ['./google-map.component.css']
})
export class GoogleMapComponent implements OnInit {

  options: any;
  overlays: any[] = [];
  dialogVisible: boolean = false;
  markerTitle?: string | null;
  selectedPosition: any;
  infoWindow: any;
  draggable: boolean = false;

  constructor(private messageService: MessageService) { }

  ngOnInit(): void {
    this.options = {
      center: { lat: 36.890257, lng: 30.707417 },
      zoom: 12
    };

    this.initOverlays();

    this.infoWindow = new google.maps.InfoWindow();
  }

  handleMapClick(event: any) {
    this.dialogVisible = true;
    this.selectedPosition = event.latLng;
  }

  handleOverlayClick(event: any) {
    let isMarker = event.overlay.getTitle != undefined;

    if (isMarker) {
      let title = event.overlay.getTitle();
      this.infoWindow.setContent('' + title + '');
      this.infoWindow.open(event.map, event.overlay);
      event.map.setCenter(event.overlay.getPosition());

      this.messageService.add({ severity: 'info', summary: 'Marker Selected', detail: title });
    }
    else {
      this.messageService.add({ severity: 'info', summary: 'Shape Selected', detail: '' });
    }
  }

  addMarker() {
    this.overlays.push(new google.maps.Marker({ position: { lat: this.selectedPosition.lat(), lng: this.selectedPosition.lng() }, title: this.markerTitle, draggable: this.draggable }));
    this.markerTitle = null;
    this.dialogVisible = false;
  }

  handleDragEnd(event: any) {
    this.messageService.add({ severity: 'info', summary: 'Marker Dragged', detail: event.overlay.getTitle() });
  }

  initOverlays() {
    if (!this.overlays || !this.overlays.length) {
      this.overlays = [
        new google.maps.Marker({ position: { lat: 36.879466, lng: 30.667648 }, title: "Konyaalti" }),
        new google.maps.Marker({ position: { lat: 36.883707, lng: 30.689216 }, title: "Ataturk Park" }),
        new google.maps.Marker({ position: { lat: 36.885233, lng: 30.702323 }, title: "Oldtown" }),
        new google.maps.Polygon({
          paths: [
            { lat: 36.9177, lng: 30.7854 }, { lat: 36.8851, lng: 30.7802 }, { lat: 36.8829, lng: 30.8111 }, { lat: 36.9177, lng: 30.8159 }
          ], strokeOpacity: 0.5, strokeWeight: 1, fillColor: '#1976D2', fillOpacity: 0.35
        }),
        new google.maps.Circle({ center: { lat: 36.90707, lng: 30.56533 }, fillColor: '#1976D2', fillOpacity: 0.35, strokeWeight: 1, radius: 1500 }),
        new google.maps.Polyline({ path: [{ lat: 36.86149, lng: 30.63743 }, { lat: 36.86341, lng: 30.72463 }], geodesic: true, strokeColor: '#FF0000', strokeOpacity: 0.5, strokeWeight: 2 })
      ];
    }
  }

  zoomIn(map: any) {
    map.setZoom(map.getZoom() + 1);
  }

  zoomOut(map: any) {
    map.setZoom(map.getZoom() - 1);
  }

  clear() {
    this.overlays = [];
  }
}

Output

Google Map in Angular

Summary

In this video, we learned how to implement Google Map in Angular projects using PrimeNG.

I hope it's helpful.

Reference

  • https://primefaces.org/primeng/showcase/#/gmap
  • https://github.com/Ankitsahu92/GMap

Thank You for your time