2016-07-04 5 views
0

Я пытаюсь использовать карту Google в моем приложении Ionic2, как описано here, однако есть ошибка new google.maps.Map строки следующим образом, и поэтому я предполагаю, что я не могу увидеть карту на моей странице:Ionic2 Google Maps API ошибка

enter image description here

enter image description here

Мои app.ts

import { Component, ViewChild, provide } from '@angular/core'; 
import { App, ionicBootstrap, Platform, Nav, Config } from 'ionic-angular'; 
import { StatusBar } from 'ionic-native'; 
import { HTTP_PROVIDERS, Http } from '@angular/http'; 
import {AuthHttp, AuthConfig} from 'angular2-jwt'; 

import { StartPage } from './pages/start/start.component'; 
import { FarmList } from './pages/farmList/farmList.component'; 
import { Slider } from './pages/slider/slider.component'; 
import { ProfilePage } from './pages/profile/profile.component'; 

@Component({ 
    templateUrl: 'build/app.html', 
    styleUrls: ['/app.scss'], 
    providers:[ 
    provide(AuthHttp, { 
     useFactory: (http) => { 
     return new AuthHttp(new AuthConfig, http); 
     }, 
     deps: [Http] 
    }) 
    ] 
}) 


export class MyApp { 
    @ViewChild(Nav) nav: Nav; 

    rootPage: any = Slider; 

    pages: Array<{title: string, component: any, name: any}> 

    constructor(private platform: Platform) { 
    this.initializeApp(); 

    // used for an example of ngFor and navigation 
    this.pages = [ 

     { title: 'Start', component: StartPage , name:'home' }, 
     { title: 'Farms', component: FarmList, name: 'list' }, 
     { title: 'Profile', component: ProfilePage, name: 'contact' }, 
    ]; 

    } 

    initializeApp() { 
    this.platform.ready().then(() => { 
     // Okay, so the platform is ready and our plugins are available. 
     // Here you can do any higher level native things you might need. 
     StatusBar.styleDefault(); 
    }); 
    } 

    openPage(page) { 
    // Reset the content nav to have just this page 
    // we wouldn't want the back button to show in this scenario 
    this.nav.setRoot(page.component); 
    } 
} 

ionicBootstrap(MyApp,[HTTP_PROVIDERS]); 

Мой index.html :

<body> 

    <ion-app></ion-app> 

    <script src="http://maps.google.com/maps/api/js"></script> 
    <!-- cordova.js required for cordova apps --> 
    <script src="cordova.js"></script> 
    <!-- Polyfill needed for platforms without Promise and Collection support --> 
    <script src="build/js/es6-shim.min.js"></script> 
    <!-- Zone.js and Reflect-metadata --> 
    <script src="build/js/Reflect.js"></script> 
    <script src="build/js/zone.js"></script> 
    <!-- the bundle which is built from the app's source code --> 
    <script src="build/js/app.bundle.js"></script> 
</body> 

Мой компонент:

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

@Component({ 
    templateUrl: 'build/pages/start/start.html' 
}) 

export class StartPage { 

    map:any 

    constructor(private navController: NavController, private platform: Platform) { 

    this.initializeMap(); 
    } 

    initializeMap() { 

     this.platform.ready().then(() => { 
      var minZoomLevel = 12; 

      this.map = new google.maps.Map(document.getElementById('map_canvas'), { 
       zoom: minZoomLevel, 
       center: new google.maps.LatLng(38.50, -90.50), 
       mapTypeId: google.maps.MapTypeId.ROADMAP 
      }); 

     }); 
    } 
} 

Мой HTML:

<ion-navbar *navbar> 
    <button menuToggle> 
    <ion-icon name="menu"></ion-icon> 
    </button> 
    <ion-title>Start</ion-title> 
</ion-navbar> 


<ion-content padding class="page1"> 

    <div padding> 
     <img src="images/icon_transperent.png" width="200"/> 
    </div> 

    <div id="map_canvas"></div> 

</ion-content> 

Мой SCSS:

#map_canvas { 
    width: 100%; 
    height: 100%; 
} 

Что именно происходит здесь не так?

UPDATE: полный скриншот консоли

enter image description here

UPDATE:

typings install dt~google.maps --global должны быть выполнены в директории проекта, в противном случае это не имеет никакого эффекта!

+0

Не могли бы вы добавить сообщение об ошибке, которое вы получаете? – sebaferreras

ответ

2

однако есть ошибка на новой линии google.maps.Map следующая и так я предполагаю, что я не могу увидеть карту на моей странице:

ошибки вы получаете что-то вроде Cannot find name google? Если так, то typescript жалуется на то, что вы не знаете ничего о себе . google объект. Это не ошибка, ваш код должен быть переполнен в любом случае.

Если вы не хотите, чтобы получить это предупреждение вы можете установить definition for google maps (так машинопись может знать его свойства и методы), выполнив:

typings install google.maps --global 

Что-то я хотел бы изменить в своем коде является:

export class StartPage { 

    // remove this line, by adding private platform : Platform as a parameter 
    // in the constructor already creates an instance of the platform 
    // platform : any 

    // I've added the private keyword to platform, remember that setting this to 
    // public/private is mandatory in the constructor, and by doing that you are 
    // creating a variable called platform and asigning it the Platform object by 
    // Dependency Injection. 
    constructor(private navController: NavController, private platform: Platform) { 

    // You don't need this because of what I say in the constructor's comment. 
    // this.platform=platform 

    this.initializeMap(); 
    } 

========================================

EDIT:

О новой ошибке, которую вы только что добавили, я думаю, проблема связана с политикой безопасности контента, которую вы определяете в index.html. Давайте попробуем добавить очень разрешительную политику, которая по сути позволит нам загружать любые ресурсы.В зависимости от вашего приложения, вы можете посмотреть на обеспечение более строгой политики, а открытая политика хороша для развития:

Измените файл www/index.html, включив в него следующий мета-тег:

<meta http-equiv="Content-Security-Policy" content="font-src 'self' data:; img-src * data:; default-src * 'unsafe-eval' 'unsafe-inline'"> 
+0

Есть ли какие-либо установки npm, прежде чем я даже попытаюсь использовать карты google в Ionic? Потому что, как только я добавлю эти ссылки на соответствующие карты Google в компоненте, мое приложение перестает работать. – Nitish

+0

Не могли бы вы добавить ошибку, которую вы получаете? – sebaferreras

+0

это: Предупреждение API Карт Google: NoApiKeys. Я также обновлю свой вопрос с помощью app.ts через мгновение – Nitish

Смежные вопросы