IONIC FRAMEWORK“ TypeError:Object(...)不是函数”

时间:2018-08-18 22:12:57

标签: javascript typescript dictionary ionic-framework google-nearby

请帮助我解决这个问题,我坚持了将近3天,这使我发疯了,几乎10次检查此代码中是否没有使用对象作为函数,im使用google map api用于附近位置帮助我来解决这个问题。 源代码如下 谢谢你,对不起我的英语

TypeError:Object(...)不是函数

Map.ts

   import { Component, NgZone } from '@angular/core';
    import { Geolocation } from '@ionic-native/geolocation';
    import { LoadingController } from 'ionic-angular';

    declare var google;

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

      map: any;
      markers: any;
      autocomplete: any;
      GoogleAutocomplete: any;
      GooglePlaces: any;
      geocoder: any
      autocompleteItems: any;
      loading: any;

      constructor(
        public zone: NgZone,
        public geolocation: Geolocation,
        public loadingCtrl: LoadingController
      ) {
        this.geocoder = new google.maps.Geocoder;
        let elem = document.createElement("div")
        this.GooglePlaces = new google.maps.places.PlacesService(elem);
        this.GoogleAutocomplete = new google.maps.places.AutocompleteService();
        this.autocomplete = {
          input: ''
        };
        this.autocompleteItems = [];
        this.markers = [];
        this.loading = this.loadingCtrl.create();
      }

      ionViewDidEnter(){
          // let infoWindow = new google.maps.InfoWindow({map: map});
          //Set latitude and longitude of some place
        this.map = new google.maps.Map(document.getElementById('map'), {
          center: {lat: -34.9011, lng: -56.1645},
          zoom: 15
        });
      }

      tryGeolocation(){
        this.loading.present();
        this.clearMarkers();//remove previous markers

        this.geolocation.getCurrentPosition().then((resp) => {
          let pos = {
            lat: resp.coords.latitude,
            lng: resp.coords.longitude
          };
          let marker = new google.maps.Marker({
            position: pos,
            map: this.map,
            title: 'I am here!'
          });
          this.markers.push(marker);
          this.map.setCenter(pos);
          this.loading.dismiss();

        }).catch((error) => {
          console.log('Error getting location', error);
          this.loading.dismiss();
        });
      }

      updateSearchResults(){
        if (this.autocomplete.input == '') {
          this.autocompleteItems = [];
          return;
        }
        this.GoogleAutocomplete.getPlacePredictions({ input: this.autocomplete.input },
          (predictions, status) => {
            this.autocompleteItems = [];
            if(predictions){
              this.zone.run(() => {
                predictions.forEach((prediction) => {
                  this.autocompleteItems.push(prediction);
                });
              });
            }
        });
      }

      selectSearchResult(item){
        this.clearMarkers();
        this.autocompleteItems = [];

        this.geocoder.geocode({'placeId': item.place_id}, (results, status) => {
          if(status === 'OK' && results[0]){
            // let position = {
            //     lat: results[0].geometry.location.lat,
            //     lng: results[0].geometry.location.lng
            // };
            let marker = new google.maps.Marker({
              position: results[0].geometry.location,
              map: this.map
            });
            this.markers.push(marker);
            this.map.setCenter(results[0].geometry.location);
          }
        })
      }

      clearMarkers(){
        for (var i = 0; i < this.markers.length; i++) {
          console.log(this.markers[i])
          this.markers[i].setMap(null);
        }
        this.markers = [];
      }

    }

**Nearby.ts**

import { Component, NgZone } from '@angular/core';
import { LoadingController } from 'ionic-angular';


declare var google;
@Component({
  selector: 'nearby-map',
  templateUrl: 'nearby.html'
})
export class NearbyPage {


  autocomplete: any;
  GoogleAutocomplete: any;
  GooglePlaces: any;
  geocoder: any
  autocompleteItems: any;
  nearbyItems: any = new Array<any>();
  loading: any;

  constructor(
    public zone: NgZone,
    public loadingCtrl: LoadingController
  ) {

    this.geocoder = new google.maps.Geocoder;
    let elem = document.createElement("div")
    this.GooglePlaces = new google.maps.places.PlacesService(elem);
    this.GoogleAutocomplete = new google.maps.places.AutocompleteService();
    this.autocomplete = {
      input: ''
    };
    this.autocompleteItems = [];
    this.loading = this.loadingCtrl.create();
  }


  updateSearchResults(){
    if (this.autocomplete.input == '') {
      this.autocompleteItems = [];
      return;
    }
    this.GoogleAutocomplete.getPlacePredictions({ input: this.autocomplete.input },
      (predictions, status) => {
        this.autocompleteItems = [];
        if(predictions){
          this.zone.run(() => {
            predictions.forEach((prediction) => {
              this.autocompleteItems.push(prediction);
            });
          });
        }
    });
  }

  selectSearchResult(item){
    this.loading.present();
    this.autocompleteItems = [];
    this.geocoder.geocode({'placeId': item.place_id}, (results, status) => {
      if(status === 'OK' && results[0]){
        this.autocompleteItems = [];
        this.GooglePlaces.nearbySearch({
          location: results[0].geometry.location,
          radius: '500',
          types: ['restaurant'], //check other types here https://developers.google.com/places/web-service/supported_types
           key: 'AIzaSyCX8vBwodNkoemWblqcmPZHaWghGGRqLgw'
        }, (near_places) => {
          this.zone.run(() => {
            this.nearbyItems = [];
            for (var i = 0; i < near_places.length; i++) {
              this.nearbyItems.push(near_places[i]);
            }
            this.loading.dismiss();
          });
        })
      }
    })
  }
}

Index.js

var __extends = (this && this.__extends) || (function () {
    var extendStatics = Object.setPrototypeOf ||
        ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
        function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
import { Injectable } from '@angular/core';
import { Cordova, CordovaProperty, Plugin, IonicNativePlugin } from '@ionic-native/core';
/**
 * @name Status Bar
 * @description
 * Manage the appearance of the native status bar.
 *
 * Requires Cordova plugin: `cordova-plugin-statusbar`. For more info, please see the [StatusBar plugin docs](https://github.com/apache/cordova-plugin-statusbar).
 *
 * @usage
 * ```typescript
 * import { StatusBar } from '@ionic-native/status-bar';
 *
 * constructor(private statusBar: StatusBar) { }
 *
 * ...
 *
 * // let status bar overlay webview
 * this.statusBar.overlaysWebView(true);
 *
 * // set status bar to white
 * this.statusBar.backgroundColorByHexString('#ffffff');
 * ```
 *
 */
var StatusBar = (function (_super) {
    __extends(StatusBar, _super);
    function StatusBar() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    /**
     * Set whether the status bar overlays the main app view. The default
     * is true.
     *
     * @param {boolean} doesOverlay  Whether the status bar overlays the main app view.
     */
    StatusBar.prototype.overlaysWebView = function (doesOverlay) { };
    ;
    /**
     * Use the default statusbar (dark text, for light backgrounds).
     */
    StatusBar.prototype.styleDefault = function () { };
    ;
    /**
     * Use the lightContent statusbar (light text, for dark backgrounds).
     */
    StatusBar.prototype.styleLightContent = function () { };
    ;
    /**
     * Use the blackTranslucent statusbar (light text, for dark backgrounds).
     */
    StatusBar.prototype.styleBlackTranslucent = function () { };
    ;
    /**
     * Use the blackOpaque statusbar (light text, for dark backgrounds).
     */
    StatusBar.prototype.styleBlackOpaque = function () { };
    ;
    /**
     * Set the status bar to a specific named color. Valid options:
     * black, darkGray, lightGray, white, gray, red, green, blue, cyan, yellow, magenta, orange, purple, brown.
     *
     * iOS note: you must call StatusBar.overlaysWebView(false) to enable color changing.
     *
     * @param {string} colorName  The name of the color (from above)
     */
    StatusBar.prototype.backgroundColorByName = function (colorName) { };
    ;
    /**
     * Set the status bar to a specific hex color (CSS shorthand supported!).
     *
     * iOS note: you must call StatusBar.overlaysWebView(false) to enable color changing.
     *
     * @param {string} hexString  The hex value of the color.
     */
    StatusBar.prototype.backgroundColorByHexString = function (hexString) { };
    ;
    /**
     * Hide the StatusBar
     */
    StatusBar.prototype.hide = function () { };
    ;
    /**
    * Show the StatusBar
    */
    StatusBar.prototype.show = function () { };
    ;
    StatusBar.decorators = [
        { type: Injectable },
    ];
    /** @nocollapse */
    StatusBar.ctorParameters = function () { return []; };
    __decorate([
        Cordova({    <!--- Showing error here --->
            sync: true
        }),
        __metadata("design:type", Function),
        __metadata("design:paramtypes", [Boolean]),
        __metadata("design:returntype", void 0)
    ], StatusBar.prototype, "overlaysWebView", null);
    __decorate([
        Cordova({
            sync: true
        }),
        __metadata("design:type", Function),
        __metadata("design:paramtypes", []),
        __metadata("design:returntype", void 0)
    ], StatusBar.prototype, "styleDefault", null);
    __decorate([
        Cordova({
            sync: true
        }),
        __metadata("design:type", Function),
        __metadata("design:paramtypes", []),
        __metadata("design:returntype", void 0)
    ], StatusBar.prototype, "styleLightContent", null);
    __decorate([
        Cordova({
            sync: true
        }),
        __metadata("design:type", Function),
        __metadata("design:paramtypes", []),
        __metadata("design:returntype", void 0)
    ], StatusBar.prototype, "styleBlackTranslucent", null);
    __decorate([
        Cordova({
            sync: true
        }),
        __metadata("design:type", Function),
        __metadata("design:paramtypes", []),
        __metadata("design:returntype", void 0)
    ], StatusBar.prototype, "styleBlackOpaque", null);
    __decorate([
        Cordova({
            sync: true
        }),
        __metadata("design:type", Function),
        __metadata("design:paramtypes", [String]),
        __metadata("design:returntype", void 0)
    ], StatusBar.prototype, "backgroundColorByName", null);
    __decorate([
        Cordova({
            sync: true
        }),
        __metadata("design:type", Function),
        __metadata("design:paramtypes", [String]),
        __metadata("design:returntype", void 0)
    ], StatusBar.prototype, "backgroundColorByHexString", null);
    __decorate([
        Cordova({
            sync: true
        }),
        __metadata("design:type", Function),
        __metadata("design:paramtypes", []),
        __metadata("design:returntype", void 0)
    ], StatusBar.prototype, "hide", null);
    __decorate([
        Cordova({
            sync: true
        }),
        __metadata("design:type", Function),
        __metadata("design:paramtypes", []),
        __metadata("design:returntype", void 0)
    ], StatusBar.prototype, "show", null);
    __decorate([
        CordovaProperty,
        __metadata("design:type", Boolean)
    ], StatusBar.prototype, "isVisible", void 0);
    StatusBar = __decorate([
        Plugin({
            pluginName: 'StatusBar',
            plugin: 'cordova-plugin-statusbar',
            pluginRef: 'StatusBar',
            repo: 'https://github.com/apache/cordova-plugin-statusbar',
            platforms: ['Android', 'iOS', 'Windows']
        })
    ], StatusBar);
    return StatusBar;
}(IonicNativePlugin));
export { StatusBar };
//# sourceMappingURL=index.js.map


//////////////////
// WEBPACK FOOTER
// ./node_modules/@ionic-native/status-bar/index.js
// module id = 283
// module chunks = 20

1 个答案:

答案 0 :(得分:1)

就像其他人所说的那样,您的问题非常广泛,您没有提及您使用的离子版本,但是我会给您一个提示。

假设您使用的是Ionic 4,那么您所有的@ionic-native/*依赖项都必须是5.0.0-beta.14版。

然后在您的app.module.ts中,这样导入依赖项: import { Geolocation } from '@ionic-native/geolocation/ngx'; 注意语句末尾的/ngx

此外,这是更详细的github问题:https://github.com/ionic-team/ionic/issues/15225

一个非常类似的问题可能会对您有所帮助:Ionic 4 native plugin geolocation gives me "Module not found: Error: Can't resolve 'rxjs/Observable'"