如何修复未定义的地图变量?

时间:2019-05-22 07:32:11

标签: angular google-maps cordova ionic4

当前正在处理ionic 4移动应用程序,我必须添加要与之交互的地图。当我启动该应用程序时,加载工作正常,但是当我想用加载之外的其他方法与地图进行交互时,我的变量未定义。

您将在本部分中看到与该问题有关的两个服务。 综上所述,在启动应用程序时,我调用loadMap()函数,然后再调用addMarker()方法。

在这种方法中,我的变量映射未定义,我也不明白为什么。

这是调用addMarker()方法的服务


import { Injectable } from '@angular/core';
import { Router } from '@angular/router';
import { getRandomString } from 'selenium-webdriver/safari';
import {Marker, MarkerOptions} from '@ionic-native/google-maps';
import {MapService} from './map.service';
const  GlobalIcon = 'compass';

@Injectable({
  providedIn: 'root'
})
export class IndiceService {
  public indices: Array<{ title: string; note: any; icon: string, id: number, lat:number, lng:number }> = [];
  constructor(private router: Router, private map : MapService) { }


  ajouterIndice(passedNote:any){ //Faire cet ajout à l'aide d'une promesse ???
    this.indices.push({
      title : 'Indice ' + (this.indices.length+1),
      note : passedNote,
      icon : GlobalIcon,
      id : this.indices.length+1,
      lat: this.getRandomInt(45,75),
      lng: this.getRandomInt(4,5),
    });

    this.map.addMarker(this.indices.length,this.indices[this.indices.length-1].note,this.indices[this.indices.length-1].lat,this.indices[this.indices.length-1].lng);
    this.router.navigate(['/home']);
  }

  isIndiceIncluded(data :any) : boolean{
    return this.indices.find(x => x.note === data) != undefined;
  }

  getRandomInt(min, max) : number {
    return Math.random() * (max - min + 1) + min;
  }

}

此服务是我的地图服务

import { Injectable } from '@angular/core';
import {
  GoogleMaps,
  GoogleMap,
  GoogleMapsEvent,
  GoogleMapOptions,
  CameraPosition,
  MarkerOptions,
  Marker,
  Environment
} from '@ionic-native/google-maps';

@Injectable({
  providedIn: 'root'
})
export class MapService {

  private map: GoogleMap;
  public markers : Array<Marker> = [];

  constructor() { }

  loadMap() {
    let mapOptions: GoogleMapOptions = {
      camera: {
         target: {
           lat: 43.783125,
           lng: 2.809419
         },
         zoom: 18,
         tilt: 30
       }
    };

    this.map = GoogleMaps.create('map', mapOptions);

    let marker: Marker = this.map.addMarkerSync({
      title: 'Ionic',
      icon: 'red',
      animation: 'DROP',
      position: {
        lat: 45.783125,
        lng: 4.809419
      },
    });
     /*marker.on(GoogleMapsEvent.MARKER_CLICK).subscribe(() => {
      alert('clicked');
    });*/
  }

  addMarker(id : number ,note : any, lat:number, lng:number){

    console.log(this.map); //write undefined

    let currentMarker : Marker = this.map.addMarkerSync({
      id : id,
      title: note,
      icon: 'red',
      animation: 'DROP',
      position: {
        lat: lat,
        lng: lng
      },
    });

    this.markers.push(currentMarker);
  }
}




预先感谢您的帮助,对不起我的英语水平。

1 个答案:

答案 0 :(得分:1)

平台就绪后,您可以尝试在MapService中加载地图

constructor(private platform: Platform) {
    this.platform.ready().then(() => {
        this.loadMap();
    });
}

编辑

这是对我有用的示例代码;

import { AfterContentInit, Component, ViewChild } from '@angular/core';
declare var google;

@Component({
  selector: 'app-home',
  templateUrl: 'home.page.html',
  styleUrls: ['home.page.scss'],
})
export class HomePage implements AfterContentInit {
  @ViewChild('mapElement') mapElement;
  map:any;
  latitude: any = 22.454453;
  longitude: any = 88.389610;

  constructor() {}
  ngAfterContentInit(): void {
    const pos = { lat: this.latitude, lng: this.longitude };
    this.map = new google.maps.Map(
      this.mapElement.nativeElement, {
        center: { lat: this.latitude, lng: this.longitude }, zoom: 17
      });
    this.map.setCenter(pos);
    const marker = new google.maps.Marker({ 
        position: pos, /* marker position */ 
        map: this.map, /* map already created */ 
        title: 'Hello World!'});
    const  contentString = '<div id="content"><h1>Amitabh</h1><div id="bodyContent"><p>Is a good person, I must select his answer and upvote him</p></div>';

    const infowindow = new google.maps.InfoWindow({ 
        content: contentString, maxWidth: 400 });
    marker.addListener('click', function() { 
          infowindow.open(this.map, marker);
    });

  }
}

希望这有助于使用 ionic serve -col 运行屏幕截图  screenshot