我正在尝试此example,在此示例中,第6步是获取错误。我尝试了一些解决方案,但是这些解决方案无效。
page.ts
import { Component, OnInit, ViewChild, ElementRef } from '@angular/core';
import { Geolocation } from '@ionic-native/geolocation/ngx';
import { PlaceDataService } from '../services/place-data.service';
declare var google: any;
@Component({
selector: 'app-add-marker',
templateUrl: './add-marker.page.html',
styleUrls: ['./add-marker.page.scss'],
})
export class AddMarkerPage implements OnInit {
@ViewChild('map', {static: false}) mapContainer: ElementRef;
map: any;
museumData = [];
constructor(
private geolocation: Geolocation,
private placeDataService: PlaceDataService) { }
ngOnInit() {
this.museumData = this.placeDataService.getMuseums();
this.displayGoogleMap();
this.getMarkers();
}
displayGoogleMap() {
const latLng = new google.maps.LatLng(28.6117993, 77.2194934);
const mapOptions = {
center: latLng,
disableDefaultUI: true,
zoom: 4,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
this.map = new google.maps.Map(this.mapContainer.nativeElement, mapOptions);
}
getMarkers() {
// tslint:disable-next-line:variable-name
for (let _i = 0; _i < this.museumData.length; _i++) {
if (_i > 0) {
this.addMarkersToMap(this.museumData[_i]);
}
}
}
addMarkersToMap(museum) {
const position = new google.maps.LatLng(museum.latitude, museum.longitude);
const museumMarker = new google.maps.Marker({ position, title: museum.name });
museumMarker.setMap(this.map);
}
}
page.html
<ion-header>
<ion-toolbar>
<ion-buttons slot="start">
<ion-back-button></ion-back-button>
</ion-buttons>
<ion-title>Museum in India</ion-title>
</ion-toolbar>
</ion-header>
<ion-content class="ion-padding">
<div #map id="map"></div>
</ion-content>
请帮助
答案 0 :(得分:1)
您应该在此处将静态标记为“ true”:
@ViewChild('map',{static:false})mapContainer:ElementRef;
之后,您的代码将正常工作。
它将是:
@ViewChild('map',{static:true})mapContainer:ElementRef;
答案 1 :(得分:0)
对我来说,问题是我尝试在构造函数中引用 nativelement。我使用 ionic 5,但与 4 相同。 将代码移动到 ionViewDidEnter() 使用 static:false 解决它。 对您来说,解决方案是:
ngOnInit() {
}
ionViewDidEnter(){
this.museumData = this.placeDataService.getMuseums();
this.displayGoogleMap();
this.getMarkers();
}