Loading

Angular – Recenter Angular Google Maps ( AGM )

Angular – Recenter Angular Google Maps ( AGM )

In this post, I’m going to show you how to Recenter Angular Google Maps ( AGM ) when location latitude and longitude value changes.

First add the agm library to your project, open a command prompt and run this command

npm install @agm/core --save

And imports the AgmCoreModulle to your app.module.ts

import { AgmCoreModule } from '@agm/core';

@NgModule({
  imports: [
    AgmCoreModule.forRoot({
      apiKey: 'YOUR_KEY' //If you don't have Google API key generate this from Google API console
    })
  ]
})

You may like: Moving Car Animation Using Mapbox

Replace the placeholder "YOUR_KEY" in the app.module.ts with your google API Key .

For demo I am implementing this in app.component you can use in your child component where required.

Now we are done with library & Google API key setup next we need to receive the latitude and longitude value from user so We can Recenter the MAP accordingly for that please use the below codes.

app.component.ts

import { Component } from '@angular/core';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent {
  name = 'Angular Google Map';
  lat: number = 51.5074;
  lng: number = 0.1278;
  lat1: number;
  lng1: number;
  constructor() {
  }

  setValue() {
    this.lat = Number(this.lat1);
    this.lng = Number(this.lng1);
    console.log(this.lat, this.lng)
  }
}

app.component.html

<h1> Your current location is: <h1>

  <div>
        <input [(ngModel)]="lat1" #ctrl="ngModel" class="form-control">
        <input [(ngModel)]="lng1" #ctrl="ngModel" class="form-control">
        <button (click)="setValue()" class="btn btn-primary">Mark</button>
    </div>


<agm-map style="height:500px" [zoom]='8' [latitude]="lat" [longitude]="lng">
  <agm-marker [latitude]="lat" [longitude]="lng" ></agm-marker>
</agm-map>

Now run the application and change the lat long value and you will see google map will be recenter with new lat log provided.

You may like: Deno - A First Look

Related Articles