How To Add Multiple Markers On Google Map In Angular

Hello Friends, In this article, we will learn how to Add Markers in Google Map in the Angular Application.

First, we need to install googlemaps in the angular project

npm install --save @types/googlemaps

Add googlemaps to the types array in tsconfig.app.json respectively in tsconfig.spec.json

{
  "extends": "./tsconfig.json",
  "compilerOptions": {
    "outDir": "./out-tsc/app",
    "types": ["googlemaps"]
  },
  "files": [
    "src/main.ts",
    "src/polyfills.ts"
  ],
  "include": [
    "src/**/*.d.ts"
  ]
}

 

Add the google maps API library in index.html

<script async defer src="https://maps.googleapis.com/maps/api/js?key=<Your API KEY>&libraries=geometry&language=en"></script>

Generate an API Key and replace it with that API Key in the above script tag in place of <Your API KEY>.

Next, let’s add a placeholder for Google Map in the app.component.html page

<div #map style="width:100%;height:450px"></div>

Now we are Initialize Google Map inside the component
put the below code in app.component.ts

import { AfterViewInit, Component, ViewChild } from '@angular/core';
declare var google: any;

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent implements AfterViewInit {
  map: any;
  @ViewChild('map') mapElement: any;
  lat = 43.879078;
  lng = -103.4615581;
  markers = [
    { lat: 22.33159, lng: 105.63233 },
    { lat: 7.92658, lng: -12.05228 },
    { lat: 48.75606, lng: -118.859 },
    { lat: 5.19334, lng: -67.03352 },
    { lat: 12.09407, lng: 26.31618 },
    { lat: 47.92393, lng: 78.58339 }
  ];
  constructor() { }

  ngAfterViewInit(): void {
    const mapProperties = {
      center: new google.maps.LatLng(this.lat, this.lng),
      zoom: 2,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    this.map = new google.maps.Map(this.mapElement.nativeElement, mapProperties);

    this.markers.forEach(location => {
      var marker = new google.maps.Marker({
        position: new google.maps.LatLng(location.lat, location.lng),
        map: this.map
      });
    });
  }
}

Now run the application map look likes below.

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories