From f4b28e4aa973f8e245628ff9c1a7e6050a1a2f6e Mon Sep 17 00:00:00 2001 From: Pato Date: Sun, 16 Feb 2020 01:33:46 -0500 Subject: [PATCH] adding clickable markers and info indows --- src/app/app.component.ts | 67 ++++++++++++++++++++++++++++++++++------ 1 file changed, 58 insertions(+), 9 deletions(-) diff --git a/src/app/app.component.ts b/src/app/app.component.ts index 09e4323..9cb497a 100644 --- a/src/app/app.component.ts +++ b/src/app/app.component.ts @@ -1,17 +1,30 @@ -import { Component, AfterViewInit, ViewChild, ElementRef } from '@angular/core'; +import { Component, AfterViewInit, ViewChild, ElementRef } from "@angular/core"; @Component({ - selector: 'app-root', - templateUrl: './app.component.html', - styleUrls: ['./app.component.css'] + selector: "app-root", + templateUrl: "./app.component.html", + styleUrls: ["./app.component.css"] }) export class AppComponent implements AfterViewInit { - title = 'angular-gmap'; - @ViewChild('mapContainer', { static: false }) gmap: ElementRef; + @ViewChild("mapContainer", { static: false }) gmap: ElementRef; map: google.maps.Map; lat = 40.73061; lng = -73.935242; + markers = [ + { + position: new google.maps.LatLng(40.73061, 73.935242), + map: this.map, + title: "Marker 1" + }, + { + position: new google.maps.LatLng(32.06485, 34.763226), + map: this.map, + title: "Marker 2" + } + ]; + + //Coordinates to set the center of the map coordinates = new google.maps.LatLng(this.lat, this.lng); mapOptions: google.maps.MapOptions = { @@ -19,18 +32,54 @@ export class AppComponent implements AfterViewInit { zoom: 8 }; + //Default Marker marker = new google.maps.Marker({ position: this.coordinates, map: this.map, - title: 'Hello World!' + title: "Hello World!" }); - ngAfterViewInit() { + ngAfterViewInit(): void { this.mapInitializer(); } - mapInitializer() { + mapInitializer(): void { this.map = new google.maps.Map(this.gmap.nativeElement, this.mapOptions); + + //Adding Click event to default marker + this.marker.addListener("click", () => { + const infoWindow = new google.maps.InfoWindow({ + content: this.marker.getTitle() + }); + infoWindow.open(this.marker.getMap(), this.marker); + }); + + //Adding default marker to map this.marker.setMap(this.map); + + //Adding other markers + this.loadAllMarkers(); + } + + loadAllMarkers(): void { + this.markers.forEach(markerInfo => { + //Creating a new marker object + const marker = new google.maps.Marker({ + ...markerInfo + }); + + //creating a new info window with markers info + const infoWindow = new google.maps.InfoWindow({ + content: marker.getTitle() + }); + + //Add click event to open info window on marker + marker.addListener("click", () => { + infoWindow.open(marker.getMap(), marker); + }); + + //Adding marker to google map + marker.setMap(this.map); + }); } }