Issue
I use Angular Maps with Angular 6.
I need to have binding between draggable marker, and google place autocomplete text field
It is almost working, but I have a strange behaviour, when I geocode the place from latlng, I can resolve the place with no problem, but field will not update the new value until I mouseover the marker.
Don’t really know what’s going on here.
Here is my code:
<form #form="ngForm" (ngSubmit)="onSubmit()">
<agm-map [latitude]="latitude" [longitude]="longitude" [scrollwheel]="false" [zoom]="zoom">
<agm-marker [latitude]="latitude" [longitude]="longitude"
(dragEnd)="markerDragEnd(latitude, longitude, $event)"
[markerDraggable]="true"></agm-marker>
</agm-map>
<input id="address" name="address" placeholder="search for location"
type="text" class="form-control input-lg" #search [(ngModel)]="tournament.venue.address">
</form>
and the component:
export class TournamentEditVenueComponent implements OnInit {
@Input() tournament: Tournament;
loading = false;
submitted = false;
error = '';
countries = COUNTRIES;
public latitude: number;
public longitude: number;
public zoom: number;
@ViewChild('search')
public searchElementRef: ElementRef;
constructor(
private mapsAPILoader: MapsAPILoader,
private ngZone: NgZone,
) {
}
markerDragEnd(lat, lng, $event: MouseEvent) {
this.latitude = $event.coords.lat;
this.longitude = $event.coords.lng;
const geocoder = new google.maps.Geocoder();
const latlng = new google.maps.LatLng(this.latitude, this.longitude);
const request = {
latLng: latlng
};
geocoder.geocode(request, (results, status) => {
this.tournament.venue.address = results[0].formatted_address;
console.log('1:' + this.tournament.venue.address);
});
}
ngOnInit() {
// set google maps defaults
this.zoom = 4;
this.latitude = parseFloat(this.tournament.venue.latitude);
this.longitude = parseFloat(this.tournament.venue.longitude);
// create search FormControl
// set current position
this.setCurrentPosition();
}
private setCurrentPosition() {
// If no registered location, set it to current browser position
if ('geolocation' in navigator && this.latitude == null && this.longitude == null) {
navigator.geolocation.getCurrentPosition((position) => {
this.latitude = position.coords.latitude;
this.longitude = position.coords.longitude;
this.zoom = 12;
});
}
}
}
What am I missing ?
Solution
Update your address inside NgZone
so that Angular detects the change:
geocoder.geocode(request, (results, status) => {
this.ngZone.run(() => {
this.tournament.venue.address = results[0].formatted_address;
})
});
Here is a demo