Is there a way to update/refresh the agm-map component?

Viewed 1435

I'm trying to update the map component in my application, I expect to refresh the location and pan the map onto the latitude and longitude that are typed in the form .

I have this at the moment:

HTML Component:

    <div class="row">
          <button (click)="refreshMap()" class="btn btn-block">Refrescar localizacion</button>
        </div>

    <agm-map
            [latitude]="myform.get('Latitude').value"
            [longitude]="myform.get('Longitude').value"
            [disableDefaultUI]="true"
            [zoom]="13"
            (mapClick)="mapClicked($event)"
            [usePanning]="true"
          >
            <agm-marker [latitude]="myform.get('Latitude').value" [longitude]="myform.get('Longitude').value"> </agm-marker>
          </agm-map>

Typescript:

 refreshMap() {
    const position = {
      coords: { lat: this.myform.controls.('latitude').value, lng: this.myform.controls.('longitude').value },
    };
    this.marker.position = position.coords;
    const currentLat = this.marker.position.lat;
    const currentLng = this.marker.position.lng;

    this.latitude.setValue(currentLat);
    this.longitude.setValue(currentLng);
 }

This way when I click the button, it pans the agm-map to the location represented by the the values that are currently on the Inputs and adds a marker in that location. I would like to do this without using a button and reactively while Typing the coordinates, like after a certain time it updates the map, but doing it through the button it works for me(I have both Inputs and the agm-map in the same screen). Is there any way I can make this possible?

1 Answers

Try below

  • Subscribe to the valueChanges property of the form. This will execute when you make any changes to the form
  • Pipe the subscription to debounceTime operator, This will ensure that a lag before the function is called
  • Pipe the Observable through distinctUntilChanged operator, we wouldn't want to call location on the same values
  import { combineLatest } from 'rxjs';
  import { debounceTime, distinctUntilChanged, tap } from 'rxjs/operators';

  latitude$ = this.myform.get('Latitude').valueChanges;
  longitude$ = this.myform.get('Longitude').valueChanges;
  formChanges$ = combineLatest([this.latitude$, this.longitude$]).pipe(
    debounceTime(1000),
    distinctUntilChanged(),
    tap(() => this.refreshMap())
  )
  ngOnInit() {
    this.formChanges$.subscribe()
  }

Related