在角度中加载谷歌地图,第一次不加载



在我的应用程序中加载了几张地图,我在页面中没有发生的错误是,在页面的第一次加载中它不会加载地图,但是当我执行无限滚动时,如果它加载地图,此页面加载了一个重定向它的 Angular 路由器。

我首先将信息加载到 ngOnInit((: void {} 中,最后执行此函数以加载映射。

我尝试使用 navParams 以不同的方式将信息传递给他,但它仍然不起作用,我还输入了 setTimeout basatante 时间,以防万一是加载时间,但它仍然不起作用

那是我的代码

async getPublications(page, adding = false) {
const loading = await this.loading.create();
loading.present();
this._publicationService.getPublicationsUser(this.token,this.id ,page).subscribe(
response => {
console.log(response);
if (response.publications) {
this.coords = [];
this.total = response.total_items;
this.pages = response.pages;
this.items_per_page = response.items_per_page
if (!adding) {
this.publications = response.publications
for (let i = 0; i < this.publications.length; i++) {
let cord = this.publications[i].location.split(',');
let object = {
lat: cord[0], lng: cord[1], zoom: 15
}
this.coords.push(object);
}
setTimeout(() => {
this.initialize();
loading.dismiss();
}, 3000);
} else {
var arrayA = this.publications;
var arrayB = response.publications;
this.publications = arrayA.concat(arrayB);
console.log(this.publications)
for (let i = 0; i < this.publications.length; i++) {
let cord = this.publications[i].location.split(',');
let object = {
lat: cord[0], lng: cord[1], zoom: 15
}
this.coords.push(object);
}
setTimeout(() => {
this.initialize();
loading.dismiss();
}, 3000);
}
} else {

loading.dismiss();
}
},
async error => {
}
)
}

initialize() {
for (var i = 0, length = this.coords.length; i < length; i++) {
var point = this.coords[i];
var latlng = new google.maps.LatLng(point.lat, point.lng);
this.maps[i] = new google.maps.Map(document.getElementById('map' + (i)), {
zoom: point.zoom,
center: latlng,
zoomControl: false,
mapTypeControl: false,
scaleControl: false,
streetViewControl: false,
rotateControl: false,
fullscreenControl: false,
gestureHandling: 'none',
});
this.markers[i] = new google.maps.Marker({
position: latlng,
map: this.maps[i]
});
}
}
<div id="{{'map'+i}}" style="max-width:500px; height:300px"></div>

我认为问题出在生成div时。你需要给 Angular 一个呼吸来创建div,然后调用来初始化。"呼吸"正在使用 setTimeout,但你不需要给 milisecons。好吧,一般的想法是在ngOnInit订阅ActivateRoute paramMap,请参阅文档

ngOnInit() {
this.route.paramMap.pipe(
switchMap((params: ParamMap) =>{
this.id=+params.get('id') //I suppose you has in params id and page
this.page=+params.get('id')
return this._publicationService.getPublicationsUser(this.token,this.id ,this.page)
}) //see that you, in some way, are subscribing to "this._publicationService"
).subscribe(res=>{
....
this.items_per_page = response.items_per_page 
this.coords=..your code.. //I suppose your *ngFor is loop over this.coords(*)
...
setTimeout(()=>{ //<--this is the "breath"
this.initialize()
})
})
}

(*( 我想说你的循环是这样的:

<div *ngFor="let coord of coords;let i=index">
<div id="{{'map'+i}}" style="max-width:500px; height:300px"></div>
</div>

如您所见,Angular 首先创建"divs"和"呼吸后"填充地图。你可以看到一个setTimeout((,就像你对Angular说的那样:"嘿,伙计!首先重新绘制应用程序,重新绘制后,请记住另一个操作">

最新更新