[英]markers on google maps using Angular 6
我在數據庫中有一個地理位置列表,並將它們存儲在這樣的變量中:
.TS
ngOnInit() {
this.getListings()
}
getListings() {
this.serviceHomeScreen.getAllListingsDetails().subscribe((data) => {
this.extractlistings(data[0])
})
}
extractlistings(data) {
this.locations = data
console.log(this.locations[1]) // has the right value
}
mapReady(map) {
console.log(this.locations[1]) // undefined
for (let i = 0; i < this.locations.length; i++) {
console.log("aici")
new google.maps.Marker({
position: { lat: this.locations[i].lat, lng: this.locations[i].long },
map: map,
});
}
}
html的
<agm-map id="map_" [zoom]="30" [fitBounds]="true" [latitude]="lat" [longitude]="lng" [streetViewControl]="false" [zoomControl]="false" (mapReady)="mapReady($event)"></agm-map>
哪里是這樣的
locations = [{'id': 1, 'lat': '43', long: '-12'}, {'id': 2, 'lat': '34', long: '-15'}, {'id': 3, 'lat': '13', long: '-12'}
]
問題是我從服務中獲取了這個locations
數組,它具有正確的值,但是當我需要從該數組中獲取經度和緯度時,在mapReady()
函數內部是undefined
。
這是為什么? mapReady
之前被調用ngOnInit
?
感謝您的時間!
mapReady(map)
是由裝置的輸出叫做<agm-map>
可能你之前發出的組件ngOnInit()
已完成完成這就是為什么你會得到undefined
的this.locations
。
嘗試在地圖准備好后獲取位置,這樣您就不會得到undefined
。
mapReady(map) {
this.serviceHomeScreen.getAllListingsDetails().subscribe((data) => {
this.locations = data[0];
for (let i = 0; i < this.locations.length; i++) {
console.log("aici")
return new google.maps.Marker({
position: { lat: this.locations[i].lat, lng: this.locations[i].long },
map: map,
});
}
})
}
另一種方法是繼續在ngOnInit
上獲取數據,但是在數據完成加載后設置一個標志,例如this.dataLoaded = true
。 然后,您將在<agm-map>
*ngIf
<agm-map>
組件模板上的*ngIf
使用此屬性,以便僅在數據准備就緒時才加載組件。 發出(mapReady)並mapReady(map)
時,數據將可用。
dataLoaded = false;
ngOnInit() {
this.getListings()
}
getListings() {
this.serviceHomeScreen.getAllListingsDetails().subscribe((data) => {
this.extractlistings(data[0]);
})
}
extractlistings(data) {
this.locations = data;
this.dataLoaded = true;
console.log(this.locations[1]); // has the right value
}
mapReady(map) {
console.log(this.locations[1]); // now defined
for (let i = 0; i < this.locations.length; i++) {
console.log("aici")
return new google.maps.Marker({
position: { lat: this.locations[i].lat, lng: this.locations[i].long },
map: map,
});
}
}
模板:
<agm-map
*ngIf="dataLoaded"
id="map_"
[zoom]="30"
[fitBounds]="true"
[latitude]="lat"
[longitude]="lng"
[streetViewControl]="false"
[zoomControl]="false"
(mapReady)="mapReady($event)">
</agm-map>
我不認為問題出在ngOnInit之前調用mapReady,但更多的是在getAllListingsDetails返回值之前調用mapReady。
由於使用的是角貼圖,因此一種避免等待地圖准備就緒的方法是使用<agm-map>
內的<agm-marker>
指令。
例如:
<agm-map>
<agm-marker *ngFor="let m of markers; let i = index"
[latitude]="m.lat"
[longitude]="m.lng"
label="{{ i + 1 }}">
<agm-info-window>
<strong>InfoWindow content</strong>
</agm-info-window>
</agm-marker>
</agm-map>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.