我正在尝试在加载页面时在地图上添加一个标记,但似乎标记根本没有显示。
home.ts
import { Component, ViewChild, ElementRef } from '@angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';
import { Geolocation } from '@ionic-native/geolocation';
import {
GoogleMaps,
GoogleMap,
GoogleMapsEvent,
Marker,
GoogleMapsAnimation,
MyLocation
} from '@ionic-native/google-maps';
declare var google;
@Component({
selector: 'page-home',
templateUrl: 'home.html',
})
export class HomePage {
@ViewChild('map') mapElement: ElementRef;
map: GoogleMap;
private markers = [];
records = [];
constructor(public navCtrl: NavController, public geolocation: Geolocation) { }
ionViewDidLoad() {
this.loadMap();
}
loadMap() {
this.geolocation.getCurrentPosition().then(position => {
let latLng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
let mapOptions = {
center: latLng,
zoom: 15,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
this.map = new google.maps.Map(this.mapElement.nativeElement, mapOptions);
});
let latLng = new google.maps.LatLng(1.3010626054202958, 103.85411771659146);
this.addMarker(latLng);
}
addMarker(latLng) {
let marker = new google.maps.Marker({
map: this.map,
animation: google.maps.Animation.DROP,
position: latLng
});
let content = "<h4>Information!</h4>";
this.markers.push(marker);
this.addInfoWindow(marker, content);
marker.setMap(this.map);
}
addInfoWindow(marker, content) {
let infoWindow = new google.maps.InfoWindow({
content: content
});
google.maps.event.addListener(marker, 'click', () => {
infoWindow.open(this.map, marker);
});
}
}
编辑: home.html
<ion-header>
<ion-navbar>
<ion-title>
Google Map - Ionic 3
</ion-title>
</ion-navbar>
</ion-header>
<ion-content padding>
<div #map id="map"></div>
</ion-content>
在this.addMarker(latLng)之后添加console.log(this.markers)显示标记已实例化并成功添加到markers数组中
我在这里做错什么了吗?
答案 0 :(得分:0)
这可能是一个更改检测问题:您的标记值在那里,但是Angular不知道这些值,也不会触发模板更改。请尝试执行以下操作,如果这不能解决问题的罪魁祸首,但至少可以消除CDR问题。之所以会发生这种情况,是因为位置数据可以在没有Angular注意力的情况下进入您的代码中。
尝试将CDR导入组件:
import { ChangeDetectorRef } from "@angular/core";
然后将其注入构造函数:
constructor(
private cdr: ChangeDetectorRef, ...
)
然后在所有数据更新后尝试使用detectChanges方法:
addMarker(latLng) {
let marker = new google.maps.Marker({
map: this.map,
animation: google.maps.Animation.DROP,
position: latLng
});
let content = "<h4>Information!</h4>";
this.markers.push(marker);
this.addInfoWindow(marker, content);
marker.setMap(this.map);
// here try cdr:
this.cdr.detectChanges()
}