How to load map marker automatically when page loaded in ionic 2?

in Ionic2 I use the fallowing code to load marker when page loaded but it shows error:

initializeMap() {

let minZoomLevel = 16;
Geolocation.getCurrentPosition().then((position) => {
this.map = new google.maps.Map(document.getElementById('map_canvas'), {
zoom: minZoomLevel,
center: new google.maps.LatLng(position.coords.latitude, position.coords.longitude),
mapTypeControl: false,
streetViewControl: false,
disableDefaultUI: true,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var trafficLayer = new google.maps.TrafficLayer();
        trafficLayer.setMap(this.map);
  });
Marker(){  
  let source = "origin";
   let image = 'assets/img/Untitled-1.png';   
   let marker = new google.maps.Marker({    
    map: this.map,
    animation: google.maps.Animation.DROP,
    position: this.map.getCenter(),
    draggable: true
    , icon: image
  }); 
  this.lastLatLng(marker,source);
}

in this code I call marker() by

ionViewDidEnter(){
  this.Marker();
}

the error shows on runtime:

view-controller.js:471 MapPage ionViewDidEnter error: Cannot read property ‘getCenter’ of null

You are settings this.map as a result of Geolocation.getCurrentPosition which is asynchronous, meaning that there is going to be a delay before this.map is actually set, but you are trying to access it as soon as the page enters.

You should make your call to add the marker inside the Geolocation call after this.map has been set.

1 Like

thanks Josh that was great help.