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

问题描述 投票:-1回答:1

请帮助我解决这个问题我坚持这近3天它让我疯了我差不多10次检查没有使用对象作为一个功能在这个代码我使用谷歌地图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
javascript typescript dictionary ionic-framework google-nearby
1个回答
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'"

© www.soinside.com 2019 - 2024. All rights reserved.