Search code examples
angularangular-google-maps

Is it possible to have a 2-way binding to latitude and longitude with angular google maps?


I'm using the following code to display a google maps on my angular app:

<agm-map id="map" [(latitude)]="lat" [zoom]="zoom" [(longitude)]="lng" [zoomControl]="false"
    [streetViewControl]="false">
  </agm-map>
<span>{{lat}} : {{lng}}</span>

On load, it works, I get the initial coordinates that I've in my controller.

If I update the lator lng in my controller, it works, both the maps and the span are correctly updated.

But when I move the map with the mouse, lat and lng are not updated.

I need to change some collections of markers depending on the location.

Is this not supported or what am I doing wrong?


Solution

  • Use centerChange output event emitter to get latitude and langitude. As @AshotAleqsanyan mentioned in the comment you can use debounceTime operator to delay the emission of values.

    component.html

    <agm-map id="map" [(latitude)]="lat" [zoom]="zoom" [(longitude)]="lng" [zoomControl]="false" (centerChange)="centerChange($event)"
        [streetViewControl]="false">
      </agm-map>
     <span>{{lat}} : {{lng}}</span>
    

    component.ts

    imports

    import { Component, OnInit } from "@angular/core";
    import { Subject } from "rxjs";
    import { debounceTime } from "rxjs/operators";
    
    export class Component implements OnInit {
      subject: Subject<LatLngLiteral> = new Subject();
    
      ngOnInit() {
        this.subject.pipe(debounceTime(300)).subscribe(details => {
          this.lat = details.lat;
          this.lng = details.lng;
        });
      }
    
      centerChange(code) {
        this.subject.next(code);
      }
    }