如何在离子2中加载页面时自动加载地图标记?

时间:2017-02-28 17:46:29

标签: google-maps angular google-maps-api-3 ionic2

在Ionic2中的

我在下载页面时使用下载代码来加载标记,但它显示错误:

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

在此代码中,我通过

调用marker()
ionViewDidEnter(){
  this.Marker();
}
  

view-controller.js:471 MapPage ionViewDidEnter错误:无法读取   物业' getCenter'为null

在@ Rohit-kumar-vinay请求之后

更新1:屏幕截图: enter image description here

2 个答案:

答案 0 :(得分:1)

您可以使用OnInit

中的@angular/core
  1. 导入OnInint

    import { Component, OnInit } from '@angular/core';
    import { Geolocation } from 'ionic-native';
    
  2. 在导出类中实现

    export class WelcomePage implements OnInit {
      map:any
    }
    
  3. 实施功能

    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;
    }
    
  4. 使用ionic2按照以下链接获取超级​​应用程序克隆 Youtube Link / Github Link

答案 1 :(得分:0)

我唯一需要做的就是在this.Marker();函数结束时调用Geolocation.getCurrentPosition()。非常感谢 Josh Morony