problem
when assign values of latitude and longitude on ngOnInt event map city or area display Empty ?
I work on angular 7 .
when assign values of latitude and longitude on ngOnInit event map city or area display empty
According to latitude and longitude city must display is New York but it display empty .
How to solve problem ?
what I try below :
import { Component, AfterViewInit, ViewChild, ElementRef } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements AfterViewInit {
title = 'angular-gmap';
@ViewChild('mapContainer', { static: false }) gmap: ElementRef;
map: google.maps.Map;
lat = 0;
lng = 0;
coordinates = new google.maps.LatLng(this.lat, this.lng);
mapOptions: google.maps.MapOptions = {
center: this.coordinates,
zoom: 8
};
marker = new google.maps.Marker({
position: this.coordinates,
map: this.map,
title: 'Hello World!'
});
ngOnInit() {
this. lat = 40.73061;
this.lng = -73.935242;
}
ngAfterViewInit() {
this.mapInitializer();
}
mapInitializer() {
this.map = new google.maps.Map(this.gmap.nativeElement, this.mapOptions);
this.marker.setMap(this.map);
}
}
Image display that map not display city
You create the coordinates
and the mapOptions
before setting lat
and lng
in ngOnInit. So the coordinates have the initial values of lat and lng: 0 and 0.
Your code can be reduced to
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements AfterViewInit {
title = 'angular-gmap';
@ViewChild('mapContainer', { static: false }) gmap: ElementRef;
// no need for instance fields that no one uses
// no need for ngOnInit
ngAfterViewInit() {
this.mapInitializer();
}
mapInitializer() {
// the coordinates are created with the correct lat and lng. Not with 0, 0
const coordinates = new google.maps.LatLng(40.73061, -73.935242);
const mapOptions: google.maps.MapOptions = {
center: coordinates,
zoom: 8
};
const marker = new google.maps.Marker({
position: coordinates,
title: 'Hello World!'
});
const map = new google.maps.Map(this.gmap.nativeElement, mapOptions);
marker.setMap(map);
}
}