Loading map once works but i cannot load map multiple times

Hello,

i’m struggling with ngCordova.

I have a page with <div id="map"></div> and a corresponding js which look like these :

    import {Page, NavController} from 'ionic-angular';
    import {Menu} from '../../components/menu/menu';

    @Page({
      templateUrl: 'build/pages/activity/activity.html',
      directives: [Menu]
    })

    export class ActivityPage {
	
      static get parameters() {
        return [[NavController]];
      }

      constructor(nav) {
        this.nav = nav;
        this.locActivity = {lat: 45.3, lng: 27.2};
        this.locUserMap = {lat: 46.2, lng: 26.5};
        this.map = null;
      }
  
      ngAfterViewInit() {
        this.loadMap();
      }
  
      loadMap(){

	this.map = new google.maps.Map(document.getElementById('map'), {
		center: this.locActivity,
		zoom: 15
	});
		
	var directionsDisplay = new google.maps.DirectionsRenderer({
		map: this.map
	});

	// Set destination, origin and travel mode.
	var request = {
		destination: this.locActivity,
		origin: this.locUserMap,
		travelMode: google.maps.TravelMode.WALKING
	};

	// Pass the directions request to the directions service.
	var directionsService = new google.maps.DirectionsService();
	directionsService.route(request, function(response, status) {
		if (status == google.maps.DirectionsStatus.OK) {
			// Display the route on the map.
			directionsDisplay.setDirections(response);
		}
	});
      }
    }

But the problem is the first time i load the page, the map works.

However, if I quit the page and load it again (or the same with different parameters), the map doesn’t shows up and does not send any error.

It show only if i call loadMap() myself once the page showed up.

What’s wrong with this code ?

If I’m not missing something, the code seems OK. This is just a wild guess, but it might be due to a caching which prevents the ngAfterViewInit() from firing again after the first load. I would suggest you to try using one of the Ionic lifecycle events.

1 Like

Try onPageDidEnter instead of ngAfterViewInit

BTW: https://github.com/SebastianM/angular2-google-maps

1 Like

Thank you @xr0master & @iignatov , this is working ! :smile:

native google maps is better or the javascript sdk?

The native google maps is smoother, faster but javascript sdk is more flexible.