[英]Property 'ELEMENT_DATA' is used before its initialization. - in Angular
[英]Property 'map' is used before its initialization. (Google Maps in Angular)
我正在一個有角度的網頁中實現google maps
,但我收到這個錯誤(該應用程序仍然有效)
編輯:只是為了澄清,地圖有效,標記也有效,我只是在我的 Visual Studio 代碼中收到錯誤,並且在我檢查網頁時沒有實現一個方法(這是地圖未初始化的例外)
src/app/app.component.ts:29:15 中的錯誤 - 錯誤 TS2729:在初始化之前使用屬性“地圖”。
29 地圖:this.map,
~~~
src/app/app.component.ts:15:3 15 地圖:google.maps.Map;
~~~ 'map' 在這里聲明。 src/app/app.component.ts:36:15 - 錯誤 TS2729:在初始化之前使用屬性“地圖”。
36 地圖:this.map,
~~~
src/app/app.component.ts:15:3
15 地圖:google.maps.Map; ~~~
'地圖'在這里聲明。
我的應用程序component.ts
import { Component, AfterViewInit, ViewChild, ElementRef } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements AfterViewInit {
title = 'maps-v1';
@ViewChild('mapContainer', {static: false}) gmap: ElementRef;
map: google.maps.Map;
lat = 37.37;
lng = -122.04;
coordinates = new google.maps.LatLng(this.lat, this.lng);
mapOptions: google.maps.MapOptions = {
center: this.coordinates,
zoom: 12,
gestureHandling:"cooperative",
};
marker = new google.maps.Marker({
position: this.coordinates,
map: this.map,
title:"Start"
});
mark2=new google.maps.Marker({
label: "TEST",
position:{lat:37.37,lng:-122.03},
map: this.map,
title:"TESTERSZ"
});
ngAfterViewInit(){
this.mapInitializer();
throw new Error('Method not implemented.');
}
mapInitializer() {
this.map = new google.maps.Map(this.gmap.nativeElement,
this.mapOptions);
this.marker.setMap(this.map);
this.mark2.setMap(this.map);
}
}
任何幫助,將不勝感激
該錯誤是因為在afterViewInit
初始化地圖之前首先初始化了標記對象
解決方案是將標記初始化移動到mapInitializer()
並將它們放在this.map = new google.maps
語句之后。
mapInitializer() {
this.map = new google.maps.Map(this.gmap.nativeElement, this.mapOptions);
const marker = new google.maps.Marker({
position: this.coordinates,
map: this.map, // this.map will contain the map object here
title:"Start"
});
const mark2 = new google.maps.Marker({
label: "TEST",
position:{lat:37.37,lng:-122.03},
map: this.map,
title:"TESTERSZ"
});
marker.setMap(this.map);
mark2.setMap(this.map);
}
你必須等待地圖初始化,所以像下面這樣改變它
mapInitializer() {
setTimeout(() => {
this.map = new google.maps.Map(this.gmap.nativeElement, this.mapOptions);
}, 500);
this.marker.setMap(this.map);
this.mark2.setMap(this.map);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.