Ionic 3 Google地图 - 地图未在Android

时间:2018-06-02 05:17:21

标签: google-maps ionic-framework

我正在尝试使用离子3的地理位置和谷歌地图,该应用程序在浏览器中正常工作:

enter image description here

但出于某种原因,当我构建apk时,我的手机上没有显示地图

enter image description here

这是地理位置.ts

import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';
import { Geolocation, Geoposition } from '@ionic-native/geolocation';

declare var google;

@IonicPage()
@Component({
  selector: 'page-geo',
  templateUrl: 'geo.html',
})
export class GeoPage {
  map: any;

  constructor(public navCtrl: NavController, public navParams: NavParams, public geo: Geolocation) { }

  ionViewDidLoad() {
    this.getPosition();
  }

  getPosition():any{
    this.geo.getCurrentPosition().then(resp => {

      this.loadMap(resp);

    }).catch((error) =>{
      console.log(error);
    })
  }
  loadMap(position: Geoposition){

let latitud = position.coords.latitude;
let longitud = position.coords.longitude;
console.log(latitud, longitud);

let mapEle: HTMLElement = document.getElementById('map');

let myLatLng = {lat: latitud, lng: longitud};

this.map = new google.maps.Map(mapEle, {
  center: myLatLng,
  zoom: 12
});



google.maps.event.addListenerOnce(this.map, 'idle', () => {
  let marker = new google.maps.Marker({
    position: myLatLng,
    map: this.map,
    title: 'Hello World!'
  });
  mapEle.classList.add('show-map');
    });

  }



}

我不知道出了什么问题,谢谢你的建议


enter image description here

1 个答案:

答案 0 :(得分:1)

您的问题是,只有在成功获取地理位置后才能致电loadMap(resp)

如果地理定位请求失败(由于权限),那么应用程序将无法加载。

您需要加载地图然后设置中心:

ionViewDidLoad() {
    this.loadmap()
    this.getPosition();
}

getPosition(): any {
    this.geo.getCurrentPosition().then(resp => {
        this.setCenter(resp);
    }).catch((error) => {
        console.log(error);
    })
}

loadMap() {
    let mapEle: HTMLElement = document.getElementById('map');
    this.map = new google.maps.Map(mapEle, {
        center: myLatLng,
        zoom: 12
    });
}

setCenter(position: Geoposition) {
    let myLatLng = { lat: position.coords.latitude, lng: position.coords.longitude };
    this.map.setCenter(myLatLng);

    google.maps.event.addListenerOnce(this.map, 'idle', () => {
        let marker = new google.maps.Marker({
            position: myLatLng,
            map: this.map,
            title: 'Hello World!'
        });
        mapEle.classList.add('show-map');
    });
}

或者,您可以在地理位置承诺的loadMap()中调用.catch(),并在没有坐标的情况下加载地图。

getPosition(): any {
    this.geo.getCurrentPosition().then(resp => {
        this.loadMap(resp);
    }).catch((error) => {
        // Load the map even if we fail
        this.loadMapFallback();
        console.log(error);
    });
}

/*
 ... old load map function
 */

loadMapFallback() {
    let mapEle: HTMLElement = document.getElementById('map');

    this.map = new google.maps.Map(mapEle, {
        zoom: 12
    });
}