javascript - 在 Ionic 2 中点击 google map 时出现 "Uncaught TypeError: ele.hasAttribute is not a function"

标签 javascript google-maps typescript ionic-framework ionic2

我一直在想办法如何管理在我的应用程序中实现谷歌地图自动完成后遇到的这个错误。我的maps.ts 文件看起来像;

import { Component, NgZone } from "@angular/core";
import {AlertController, NavController, Platform, NavParams,ModalController } from 'ionic-angular';
import { GoogleMap, GoogleMapsEvent, GoogleMapsLatLng, GoogleMapsMarkerOptions, CameraPosition } from 'ionic-native';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import { Geolocation } from 'ionic-native';
declare var google:any;
declare var window: any;
import {MapsAPILoader} from 'angular2-google-maps/core';
import { ConnectivityService } from '../../providers/connectivity-service';


@Component({
  selector: 'maps-page',
  templateUrl: 'maps.html'
})
export class MapsPage {
    map: any;
    firstTime : boolean = true;
    isDisplayOfflineMode : boolean = false;
  //private map: GoogleMap;

  constructor(private _navController: NavController,
    private zone: NgZone,
    private  _loader : MapsAPILoader,
    private connectivityService:ConnectivityService,
    private platform: Platform,
    public navParams: NavParams,
    public modalCtrl:ModalController,
    private alert : AlertController,
    private _zone: NgZone) {

    this.platform.ready().then(() => this.onPlatformReady());
    this.map = {
            lat: 0,
            lng: 0,
            zoom: 15
        };
        this.platform.ready().then(() => this.onPlatformReady());
        this.NetworkConnectivity();
  }
  private onPlatformReady(): void {

  }


  ngAfterViewInit() {
    GoogleMap.isAvailable().then(() => {
      this.map = new GoogleMap('map_canvas');
      this.map.one(GoogleMapsEvent.MAP_READY).then((data: any) => {
        this._zone.run(() => {
          let myPosition = new GoogleMapsLatLng(45.495586, -73.574709);
          let position: CameraPosition = {
            target: myPosition,
            zoom: 15
          };
          console.log("My position is", myPosition);
          this.map.moveCamera(position);
        });

      });
    });
  }


  submit() {
    let that = this;
    this.map.getCameraPosition().then(res => {
      let callback = that.navParams.get("callback")
      callback(res.target).then(() => {
        this._navController.pop();
      });
    })
  }
  dismiss() {
    this._navController.pop()
  }


    NetworkConnectivity(){
        setInterval(() => {
            if(this.connectivityService.isOnline()){

                if (this.firstTime)
                {
                    this.loadMap();
                    this.autocomplete()
                }

            } else {
                if(!this.isDisplayOfflineMode)
                    this.displayOffline();

            }
        }, 2000);


    }

    displayOffline() {
        this.isDisplayOfflineMode = true;
        let alert = this.alert.create({
            title: 'Network connectivity',
            subTitle: 'Offline',
            buttons: [{
                text : 'Retry',
                handler: () => {
                    this.isDisplayOfflineMode = false;
                }
            }]

        });
        alert.present();
    }


    autocomplete() {
        this._loader.load().then(() => {
            let autocomplete = new google.maps.places.Autocomplete( document.getElementById('autocomplete').getElementsByTagName('input')[0], {});
            google.maps.event.addListener(autocomplete, 'place_changed', () => {
                let place = autocomplete.getPlace();
                this.map.lat  = place.geometry.location.lat();
                this.map.lng = place.geometry.location.lng();
                console.log(place);
            });
        });
    }


    loadMap(){

        Geolocation.getCurrentPosition().then((position) => {

            this.map = {
                lat: position.coords.latitude,
                lng: position.coords.longitude,
                zoom: 15
            };
            this.firstTime = false;
        }, (err) => {
        });

    }

   getDirections() { 
    window.location = `geo:${this.map.lat},${this.map.lng};u=35`; 
  }


}

我的 html 文件看起来像;

<ion-header>
  <ion-toolbar>
    <ion-title>
      {{'SEARCHFORM.SELECT' | translate}}
    </ion-title>
    <ion-buttons start>
      <button ion-button (click)="dismiss()">
        <span ion-text color="primary" showWhen="ios">{{'SEARCHFORM.CANCEL' | translate}}</span>
        <ion-icon name="md-close" showWhen="android,windows"></ion-icon>
      </button>
    </ion-buttons>
  </ion-toolbar>
</ion-header>
<ion-content>
  <ion-fab left bottom>
        <button ion-fab class="fab-map" (click)="getDirections()">
            <ion-icon name="navigate"></ion-icon>
        </button>
    </ion-fab>

    <ion-item>
        <ion-input id="autocomplete" type="text" name="title" placeholder="Enter Address"></ion-input>
    </ion-item>

    <sebm-google-map id="map" [latitude]="map.lat" [longitude]="map.lng" [zoom]="map.zoom" >
        <sebm-google-map-marker [latitude]="map.lat" [longitude]="map.lng">
            <sebm-google-map-info-window>
                <strong>My location</strong>
            </sebm-google-map-info-window>
        </sebm-google-map-marker>
    </sebm-google-map>
  <div style="height: 100%;" id="map_canvas"></div>
</ion-content>
<ion-footer>
     <button ion-button (click)="submit()">{{'SEARCHFORM.SUBMIT' | translate}}</button>
</ion-footer>

在我实现谷歌地图自动完成功能之前, map 工作得很好,但现在每当我点击屏幕上的任何地方,它就会崩溃。有谁知道如果有人经历过它为什么会发生以及可能的解决方案是什么?我的 html 文件看起来不错吗?或者还有其他什么问题。非常感谢!!

最佳答案

使用 @ViewChildElementRef,而不是 document.getElementById('autocomplete').getElementsByTagName('input')[0]在 Angular/Ionic 2 中获取 htmlelements。

import {ViewChild,ElementRef} from '@angular/core';

@Component({
  selector: 'maps-page',
  templateUrl: 'maps.html'
})
export class MapsPage {
  @ViewChild('autocomp')
  aComplete:ElementRef;

  //...
    autocomplete() {
        this._loader.load().then(() => {
            let autocomplete = new google.maps.places.Autocomplete(this.aComplete.nativeElement.querySelector('input'));

您需要使用querySelector,因为ionic将html元素封装在ion-input中。检查this answer

在您的 html 中使用 #autocomp 作为元素的 id。

<ion-input #autocomp id="autocomplete" type="text" name="title" placeholder="Enter Address"></ion-input>

引用:ElementRef , ViewChild

关于javascript - 在 Ionic 2 中点击 google map 时出现 "Uncaught TypeError: ele.hasAttribute is not a function",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43302181/

相关文章:

javascript - 使用键和数组 typescript 编写一个对象

javascript - JSON 回调中光标不会恢复为默认值

javascript - dc.js d3+crossfilter.top 将过滤后的数据导出到CSV

javascript - 如何记录多个复选框的选择顺序?

iphone - 如何使用 GeoLocation 在 map 上定位标记?

javascript - 将 Google map 多边形路径转换为 ​​SVG 路径

rest - 需要帮助理解 angular2 中的接口(interface)和/或抽象类

javascript - 调用 http 函数时不会触发 XHR 请求

google-maps - 如何在谷歌地图中提取大头针的纬度/经度?

javascript - typescript :将元组映射到联合类型似乎在嵌套对象中不起作用