Reputation: 1151
I'm building a mobile app using ionic/angular the page I have created has a google map that works fine on first load/access but when navigating back then back again the map page the map gets blank or not rendering!!
This issue happens on mobile sizes only! and if I did touch or click anywhere gets working again but not on initialization as screenshot down shows.
Here's a stackblitz
https://stackblitz.com/edit/ionic-4-angular-8-start-template-xx3btx?file=src%2Fapp%2Ftab2%2Ftab2.page.ts
Just click on the button on the home page click here
you will see that works fine the first time, So just navigate back by the button under the title ( don't use the back for stackblitz ) then go to the page again and you will see that the map went all blank.
There are no errors showing on console;
My code:
@ViewChild('map', { static: true }) mapElement: ElementRef;
map: any;
activeLocation: any;
ngOnInit() {
this.loadMap();
}
loadMap() {
this.loadingService.present('Loading, please wait...');
let latLng = new google.maps.LatLng(29.2865163, 47.9916857);
let mapOptions = {
center: latLng,
zoom: 12,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
this.map = new google.maps.Map(this.mapElement.nativeElement, mapOptions);
var marker, i;
let th = this;
google.maps.event.addListenerOnce(this.map, 'resize', function () {
google.maps.event.trigger(this.map, 'resize');
});
this.wooService.kefanBranchesLocations().then(
locations => {
this.loadingService.dismiss();
for (i = 0; i < locations.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i]['lat'], locations[i]['lng']),
animation: google.maps.Animation.DROP,
map: this.map
});
google.maps.event.addListener(marker, 'click', (function (marker, i) {
return function () {
th.activeLocation = locations[i];
th.activeLocation['open_hours'] = typeof th.activeLocation['open_hours'] == 'string' ? JSON.parse(th.activeLocation['open_hours']) : th.activeLocation['open_hours'];
console.log(th.activeLocation);
}
})(marker, i));
}
}
);
}
HTML:
<div #map id="map"></div>
CSS:
#map {
position: absolute;
width: 100%;
height: 100%;
}
A screenshot:
Upvotes: 1
Views: 1109
Reputation: 13515
You should implement AfterContentInit
and move your code from ngOnInit()
into ngAfterContentInit()
.
Angular won't have created the map element at the init stage. You need to check later in the page lifecycle.
Check the official docs for more info: https://angular.io/guide/lifecycle-hooks.
Upvotes: 1