angulargoogle-mapsgoogle-maps-markersangular-google-mapsagm

Updating address fields with matGoogleMapsAutocomplete when dragging map marker


I am trying to implement google maps in my project using agmCore npm module.

So when i search an address in input box with matGoogleMapsAutocomplete directive. The map cordinates are updated too, and the marker is moved in the map, along with updating Country, city and postal_code fields.

But i want to trigger update of the city, state and postal code whenever i drag the map marker to new place. How can i achieve that?

Here's my code

HTML:

<div class="container" fxLayout="column" fxLayoutAlign="center">
    <div fxFlex>
        <agm-map [latitude]="latitude" [longitude]="longitude" [scrollwheel]="false" [usePanning]="true" [zoom]="zoom"
            (mapClick)="markerDragEnd($event)">
            <agm-marker [latitude]="latitude" [longitude]="longitude" [markerDraggable]="true"
                (dragEnd)="markerDragEnd($event)"> </agm-marker>
        </agm-map>
    </div>
</div>
<input placeholder="Street, house no. or flat number" class="mb-2 mt-2" matInput matGoogleMapsAutocomplete
    address="formatted_address" [country]="in" (onAutocompleteSelected)="onAutocompleteSelected($event)"
    (onLocationSelected)="onLocationSelected($event)" formControlName="AddressLine1" />

TS:


onAutocompleteSelected(results: PlaceResult) {
    if (
      results &&
      results.address_components &&
      results.address_components.length
    ) {
      results.address_components.forEach((element) => {
        if (element.types[0] == "country") {
          this.KycDetailsForm.get("Country").setValue(element.long_name);
        } else if (element.types[0] == "postal_code") {
          this.KycDetailsForm.get("PostalCode").setValue(element.long_name);
        } else if (element.types[0] == "locality") {
          this.KycDetailsForm.get("City").setValue(element.long_name);
        }
      });
    }
  }

  onLocationSelected(location: Location) {
    this.latitude = location.latitude;
    this.longitude = location.longitude;
  }

markerDragEnd($event) {
    this.latitude = $event.coords.lat;
    this.longitude = $event.coords.lng;
  }

Solution

  • i got the solution for this, for geocoding the location from map pointer to text fields:

    stackblitz link