Ionic Google Map在设备或-l Lab视图中不起作用,但在浏览器中起作用

时间:2018-12-04 23:56:53

标签: google-maps ionic-framework ionic3 ionic-view google-geolocation

我正在使用Google Map Place api创建附近的餐厅,但是当它在浏览器视图上启动时,它可以正常运行,但不能在设备或实验室视图中使用,我正在尝试在Google github stackoverflow上进行所有搜索,但没有任何效果帮助我解决这个问题,挽救我的生命。 预先谢谢你。

问题出在地理定位要素策略中,我尝试了所有方法,但没有任何方法可以解决我的问题。 我的home.ts页面代码中有问题,但我不知道是什么实际问题。 Error Shown During Lab View

Home.ts

import { Component, ViewChild ,ElementRef } from '@angular/core';
import { NavController } from 'ionic-angular';
import { Geolocation ,GeolocationOptions ,Geoposition ,PositionError } from '@ionic-native/geolocation'; 


declare var google;

@Component({
    selector: 'page-home',
    templateUrl: 'home.html'
})
export class HomePage {

@ViewChild('map') mapElement: ElementRef;
options : GeolocationOptions;
currentPos : Geoposition;
map: any;
places : Array<any> ;



constructor
(
    public navCtrl: NavController,
    private geolocation : Geolocation,



    ) { } 



ionViewDidEnter(){
    this.getUserPosition();
}    




getUserPosition(){
    this.options = {
    enableHighAccuracy : false
    };
    this.geolocation.getCurrentPosition(this.options).then((pos : Geoposition) => {

        this.currentPos = pos;     

        console.log(pos);
        this.addMap(pos.coords.latitude,pos.coords.longitude);

    },(err : PositionError)=>{
        //console.log("error : " + err.message);
    ;
    })
}

getRestaurants(latLng)
{
    var service = new google.maps.places.PlacesService(this.map);
    let request = {
        location : latLng,
        radius : 3000 ,
        types: ["restaurant"]
    };
    return new Promise((resolve,reject)=>{
        service.nearbySearch(request,function(results,status){
            if(status === google.maps.places.PlacesServiceStatus.OK)
            {
                resolve(results);    
            }else
            {
                reject(status);
            }

        }); 
    });

}

createMarker(place)
{
    let marker = new google.maps.Marker({
    map: this.map,
    animation: google.maps.Animation.DROP,
    position: place.geometry.location
    });   
}  

addMap(lat,long){

    let latLng = new google.maps.LatLng(lat, long);

    let mapOptions = {
    center: latLng,
    zoom: 5,
    mapTypeId: google.maps.MapTypeId.ROADMAP
    }

    this.map = new google.maps.Map(this.mapElement.nativeElement, mapOptions);

    this.getRestaurants(latLng).then((results : Array<any>)=>{
        this.places = results;
        for(let i = 0 ;i < results.length ; i++)
        {
            this.createMarker(results[i]);
        }
    },(status)=>console.log(status));

    this.addMarker();
}


addMarker(){

    let marker = new google.maps.Marker({
    map: this.map,
    animation: google.maps.Animation.DROP,
    position: this.map.getCenter()
    });

    let content = "<p>This is your current position !</p>";          
    let infoWindow = new google.maps.InfoWindow({
    content: content
    });

    google.maps.event.addListener(marker, 'click', () => {
    infoWindow.open(this.map, marker);
    });

}
}

Home.html

<ion-content>

  <div #map id="map"></div> 

  <div style="width : 100% ;height: 60%">
      <ion-list>

      <ion-item *ngFor="let place of places">
          <h4>{{place.name}}</h4>
          <p>{{place.vicinity}}</p>
          <p>Rating {{place.rating}}</p>
          <button ion-button clear item-end *ngIf="(place.opening_hours && !place.opening_hours.open_now)">CLOSED</button>
          <button ion-button clear item-end *ngIf="(place.opening_hours && place.opening_hours.open_now)">OPEN NOW</button>
      </ion-item>
      </ion-list>

  </div>


  </ion-content>


Index.html

<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
  <meta charset="UTF-8">
  <title>Shapekit</title>
  <meta name="viewport" content="viewport-fit=cover, width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no">
  <meta name="format-detection" content="telephone=no">
  <meta name="msapplication-tap-highlight" content="no">

  <link rel="icon" type="image/x-icon" href="assets/icon/logo.png">
  <link rel="manifest" href="manifest.json">
  <meta name="theme-color" content="#4e8ef7">

  <!-- add to homescreen for ios -->
  <meta name="apple-mobile-web-app-capable" content="yes">
  <meta name="apple-mobile-web-app-status-bar-style" content="black">

  <!-- cordova.js required for cordova apps (remove if not needed) -->
  <script src="cordova.js"></script>

  <!-- un-comment this code to enable service worker
  <script>
    if ('serviceWorker' in navigator) {
      navigator.serviceWorker.register('service-worker.js')
        .then(() => console.log('service worker installed'))
        .catch(err => console.error('Error', err));
    }
  </script>-->

  <link href="build/main.css" rel="stylesheet">

  <script>
    if ('serviceWorker' in navigator) {
      navigator.serviceWorker.register('service-worker.js')
        .then(() => console.log('service worker installed'))
        .catch(err => console.error('Error', err));
    }
  </script>

</head>
<body>

  <!-- Ionic's root component and where the app will load -->
  <ion-app></ion-app>

  <!-- The polyfills js is generated during the build process -->
  <script src="build/polyfills.js"></script>

  <!-- The vendor js is generated during the build process
       It contains all of the dependencies in node_modules -->
  <script src="build/vendor.js"></script>

  <!-- The main bundle js is generated during the build process -->
  <script src="build/main.js"></script>


  <script src="http://maps.google.com/maps/api/js?key=APIKEY&libraries=places"></script>

</body>
</html>

1 个答案:

答案 0 :(得分:1)

考虑使用平台服务而不是使用ionViewDidEnter

import { Component } from '@angular/core';
import { Platform } from 'ionic-angular';

@Component({...})
export MyApp {
  constructor(public plt: Platform) {
    this.plt.ready().then((readySource) => {

      this.getUserPosition();

    });
  }
}

ionViewDidEnter()方法基于导航。因此,要确保在设备准备就绪时实际运行代码,请使用平台服务。