Как исправить неопределенную переменную карты? - PullRequest
0 голосов
/ 22 мая 2019

В настоящее время работаю над мобильным приложением 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 Ответ

1 голос
/ 22 мая 2019

Не могли бы вы попробовать загрузить карту в 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);
    });

  }
}

Надеюсь, это поможет Скриншот работает с использованием ионная подача -col screenshot

...