Usare Google Maps in Angular

Mattepuffo's logo
Usare Google Maps in Angular

Usare Google Maps in Angular

Come sapete ormai per usare qualsiasi strumento di Google avete bisogno di configurare 200 cose.

In questo articolo do per scontato che lo abbiate fatto; compresa la creazione della API_KEY.

Quindi, partiamo dall'installazione della libreria ufficiale per Angular di Google Maps:

npm install @angular/google-maps

Il secondo step è aggiungere il modulo nel file app.module.ts:

import {NgModule} from '@angular/core';
import {BrowserModule} from '@angular/platform-browser';
import {AppComponent} from './app.component';
import {GoogleMapsModule} from '@angular/google-maps';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    GoogleMapsModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})

export class AppModule {
}

Nel file index.html dovete aggiungere il richiamo alla libreria indicando la vostra API_KEY:

<script src="https://maps.googleapis.com/maps/api/js?key=API_KEY"></script>

Poi nel componente:

import {Component, OnInit, ViewChild} from '@angular/core';
import {MapInfoWindow, MapMarker} from '@angular/google-maps';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})

export class AppComponent implements OnInit {

  @ViewChild(MapInfoWindow) infoWindow: MapInfoWindow | undefined;

  display: any;
  zoom = 10;

  center: google.maps.LatLngLiteral = {
    lat: 41.9046319,
    lng: 12.4957006
  };

  markerOptions: google.maps.MarkerOptions = {
    draggable: false
  };

  markerPositions: google.maps.LatLngLiteral[] = [];

  constructor() {}

  ngOnInit(): void {
    this.addMarker(this.center);
  }

  moveMap(event: google.maps.MapMouseEvent): void {
    if (event.latLng != null) this.center = (event.latLng.toJSON());
  }

  move(event: google.maps.MapMouseEvent): void {
    if (event.latLng != null) this.display = event.latLng.toJSON();
  }

  addMarker(event: google.maps.LatLngLiteral) {
    this.markerPositions.push(event);
  }

  openInfoWindow(marker: MapMarker) {
    if (this.infoWindow != undefined) {
      this.infoWindow.open(marker);
    }
  }

}

Abbiamo già aggiunto un marker con una info window che si apre al click.

Infine l'HTML del componente:

<google-map height="400px" width="750px" [center]="center" [zoom]="zoom" (mapClick)="moveMap($event)"
            (mapMousemove)="move($event)">

  <map-marker #marker="mapMarker"
              *ngFor="let markerPosition of markerPositions" [position]="markerPosition"
              [options]="markerOptions" (mapClick)="openInfoWindow(marker)"></map-marker>

  <map-info-window>CIAO!!</map-info-window>

</google-map>

<div>Latitudine: {{display?.lat}}</div>
<div>Longitudine: {{display?.lng}}</div>

Enjoy!


Condividi

Commentami!