how to load map marker automatically when page loa

2019-09-20 02:26发布

问题:

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();
}

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

Update 1: screenshot after @Rohit-kumar-vinay request:

回答1:

You can use OnInit from @angular/core

  1. Import OnInint

    import { Component, OnInit } from '@angular/core';
    import { Geolocation } from 'ionic-native';
    
  2. Implement in export class

    export class WelcomePage implements OnInit {
      map:any
    }
    
  3. Implement function

    ngOnInit() {
      this.map = this.initMap();
    }
    
    initMap(): Promise<void> {
    let promise: Promise<void> = new Promise<void>((resolve, reject) => {
    Geolocation.getCurrentPosition().then((position) => {
    
    let latLng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
    let GooleMap = new google.maps.Map(document.getElementById('map'), {
      center: latLng,
      zoom: 18
    });
    let marker = new google.maps.Marker({
      position: latLng,
      map: GooleMap,
      title: 'My Location',
    });
    });
    });
    return promise;
    }
    

follow below links for uber app clone using ionic2 Youtube Link / Github Link



回答2:

the only thing that i had to do is that call this.Marker(); at the end of Geolocation.getCurrentPosition() function. many thanks to Josh Morony.