Angular

Angular google maps (agm) complete guide tutorial

Spread the love

Angular google maps (agm) complete guide tutorial
Angular google maps (agm) complete guide tutorial

List of google map API features you will learn in agm maps complete tutorial

First we will install all the dependency library for the complete google map for a complete application

Step:1 – Install dependency library for google map

npm i @agm/core --save
npm i js-marker-clusterer --save
npm i @agm/snazzy-info-window --save
npm i @types/googlemaps --save

 

Step:2 – Import the AgmCoreModule in AppModule and set API key

Step:3 – Add html code. We discuss all the map selectors, directives and event in Step – 9

Step: 4 – Add CSS code in componet.css file

agm-map {
  height: 300px;
}

Step:5 – Create snazzy-info-window.css file in assets folder and link it to in angular.json styles array

Find this css file in github repository.

Step:6 – Google map cluster view style and calculator directives

# html
  <agm-marker-cluster
    [maxZoom]="clulster_max_zoom"
    [minimumClusterSize]="minClusterSize"
    [styles]="mapOptions.styles"
    [calculator]="mapOptions.calculator"
    [maxZoom]="6"

maxZoom = > this directive is use to zoom the map after click on cluster icon.

minimumClusterSize => minimumClusterSize is use to detect minimum number of markers point under a cluster.

styles = > It is use to modify cluster icon and cluster design.

calculator => It is use to return a string as you want to display in your cluster. ie if you want to display number of markers present under a cluster and minimum price among markers. Find the below code bold points in ts file.

  mapOptions = {
    styles: [
      {
        url: "./assets/images/cluster.png",
        width: 70,
        height: 50,
        textColor: "rED",
        fontWeight: "bold",
        textSize: "14px",
        fontFamily: "nunito",
        lineHeight: "12px",
        paddingTop: "8px",
        backgroundSize: "cover"
      }
    ],
    calculator: markers => {
      for (let i = 0; i < markers.length; i++) {
        // you have access all the markers from each cluster
      }
      return {
        text: markers.length + " MARKERS",
        index: 1
      };
      // index: 1 -> for green icon
      // index: 2 -> for red icon
    }
  };

Step:7 – Google map dragEnd event listener to load marker from api as per send center latitude and longitude from your end

#html
	<agm-map
                (mapClick)="mapClicked($event)"
                (centerChange)="centerChange($event)"
		(mapReady)="mapReady($event)"
#ts file
  centerChange(coords: LatLngLiteral) {
    //console.log(event);
    this.centerLatitude = coords.lat;
    this.centerLongitude = coords.lng;
  }
mapReady(map) {
               map.addListener('dragend', () => {
			this.loader = true;
			//console.log(this.centerLatitude, this.centerLongitude)
			// do something with centerLatitude/centerLongitude
		});
           }

centerChange =>Call the event on drag the map by the mouse. To track latitude and longitude points centerChange and mapReady work together.

mapReady => map is ready to display call this event. You can trap latitude and longitude points by dragend event listener in mapready function.

mapClick => This event is call in event single click on the map and that pass map coordinates points.

Step:8 – Google map marker

<agm-marker
      *ngFor="let m of markers | async; let i = index"
      (markerClick)="clickedMarker(m.label, i)"
      [latitude]="m.lat"
      [iconUrl]="{
			url: './assets/images/map-marker.png'
		}"
      [longitude]="m.lng"
      [label]="{

                        text: m.label,
			color: 'red',
			fontWeight: 'bold',
		}"
      [markerDraggable]="false"
      (dragEnd)="markerDragEnd(m, $event)"

markerClick = > Call this event on a particular marker click. According to your application workflow functionality you can use this event. We use to identify the index marker in this tutorial.

iconUrl => This directive is help you to modify custom marker icon.

label = > lable is use for add the dynamic text of marker and add style for marker

Step:9 – Google map zoom control position

Prerequisite:
1. install types/googlemap npm package

# in html after ready the mapReady event fire that call to mapReady function in ts

<agm-map
  (mapReady)="mapReady($event)" 

# in ts add the map.setOptions block in mapReady function

mapReady(map) {
    map.setOptions({
      zoomControl: "true",
      zoomControlOptions: {
        position: google.maps.ControlPosition.TOP_RIGHT
      }
    });

Step:10 – Google map customize info window

# in html configure the directive as require in your app
   <agm-snazzy-info-window
        [isOpen]="isInfoWindowOpen(i)"
        [latitude]="m.lat"
        [longitude]="m.lng"
        [closeWhenOthersOpen]="true"
        [closeOnMapClick]="true"
        [showCloseButton]="false"
        [openOnMarkerClick]="true"
        [wrapperClass]="'info-window'"
        #infoWindow
      >
        <ng-template>{{m.event_info}}</ng-template>
      </agm-snazzy-info-window>

wrapperClass=> responsible for style guide of snazzy-info-window

closeOnMapClick=> close snazzy-info-window on true

showCloseButton=> close button display hide/display on true

openOnMarkerClick => click on marker open snazzy-info-window on true

Step:11 – Google map search autocomplete with current position

Prerequisite:
1. Import ReactiveFormsModule in AppModule
2. Install types/googlemap npm package

#html

<div class="form-group">
  <input
    placeholder="search for location"
    autocorrect="off"
    autocapitalize="off"
    spellcheck="off"
    type="text"
    class="form-control"
    #search
    [formControl]="searchControl"
  />
</div>
import { MapsAPILoader } from "@agm/core";
import { FormControl } from "@angular/forms";

public searchControl: FormControl;
@ViewChild("search", { static: false }) searchElementRef: ElementRef; 
 ngOnInit(): void {
    //create search FormControl
    this.searchControl = new FormControl();
    this.searchControl.setValue("EUROPE");
    //set current position
    //this.setCurrentPosition();

    //load Places Autocomplete
    this.mapsAPILoader.load().then(() => {
      let autocomplete = new google.maps.places.Autocomplete(
        this.searchElementRef.nativeElement,
        {
          types: ["address"]
        }
      );
      autocomplete.addListener("place_changed", () => {
        this.ngZone.run(() => {
          //get the place result
          let place: google.maps.places.PlaceResult = autocomplete.getPlace();

          //verify result
          if (place.geometry === undefined || place.geometry === null) {
            return;
          }

          //set latitude, longitude and zoom
          this.lat = place.geometry.location.lat();
          this.lng = place.geometry.location.lng();
          this.map_zoom = 12;
        });
      });
    });
    
  }

  private setCurrentPosition() {
    if ("geolocation" in navigator) {
      navigator.geolocation.getCurrentPosition(position => {
        this.lat = position.coords.latitude;
        this.lng = position.coords.longitude;
        this.map_zoom = 12;
      });
    }
  }

Hope you learn lot from this tutorial please you have been solved your requirement. Please give your valuable feedback. If you have any kind of questions or issues about this article, please let me know. Please see my others interesting articles, share and subscribe my blog to get the latest updates. Thank you.

Follow others articles

Code repository:

PROJECT ON GITHUB

PROJECT ON STACKBLITZ

Thank you! please don’t forget to like and share our Facebook page to get more interesting updates.


Spread the love
Tagged , , , , , , , , , , ,

About Chandra

Technology lover. Professionally Software Developer and write some Technical Blog to help newcomer.
View all posts by Chandra →

5 thoughts on “Angular google maps (agm) complete guide tutorial

Leave a Reply

Your email address will not be published.