我正在使用 agm-core 组件在我的应用程序中使用 Google 地图。地图显示正常。在我的 app.module.ts 中,我有以下内容:
AgmCoreModule.forRoot({
apiKey: '', // API key is defined here.
libraries: ['places', 'drawing', 'geometry'] })
在我的 html 中,我有:
<ion-header></ion-header>
<ion-toolbar>
</ion-toolbar>
<div class="form-group">
<label>Enter address</label>
<input type="text" class="form-control
(keydown.enter)="$event.preventDefault()" placeholder="Search Nearest
Location" autocorrect="off" autocapitalize="off" spellcheck="off"
type="text" #search>
</div>
<agm-map
[latitude]="latitude"
[longitude]="longitude"
[zoom]="zoom" >
<agm-marker
[latitude]="latitude"
[longitude]="longitude"></agm-marker>
</agm-map>
<h5>Address: {{address}}</h5>
<div>Latitude: {{latitude}}</div>
<div>Longitude: {{longitude}}</div>
我的 ts 文件是:
export class SiteDetailsComponent implements OnInit {
title = 'AGM project';
latitude: number;
longitude: number;
zoom: number;
address: string;
private geoCoder;
@ViewChild('search', { static: true })
public searchElementRef: ElementRef;
constructor(
private router: Router,
private mapsAPILoader: MapsAPILoader,
private ngZone: NgZone
) {}
ngOnInit() {
// load Places Autocomplete
this.mapsAPILoader.load().then(() => {
this.setCurrentLocation();
this.geoCoder = new google.maps.Geocoder();
const autocomplete = new google.maps.places.Autocomplete(this.searchElementRef.nativeElement, {
types: ['address']
});
autocomplete.addListener('place_changed', () => {
this.ngZone.run(() => {
// get the place result
const place: google.maps.places.PlaceResult = autocomplete.getPlace();
// verify result
if (place.geometry === undefined || place.geometry === null) {
return;
}
// set latitude, longitude and zoom
this.latitude = place.geometry.location.lat();
this.longitude = place.geometry.location.lng();
this.zoom = 12;
});
});
});
}
// Get Current Location Coordinates
private setCurrentLocation() {
if ('geolocation' in navigator) {
navigator.geolocation.getCurrentPosition((position) => {
this.latitude = position.coords.latitude;
this.longitude = position.coords.longitude;
this.zoom = 8;
this.getAddress(this.latitude, this.longitude);
});
}
}
getAddress(latitude, longitude) {
this.geoCoder.geocode({ location: { lat: latitude, lng: longitude } }, (results, status) => {
if (status === 'OK') {
if (results[0]) {
this.zoom = 12;
this.address = results[0].formatted_address;
} else {
}
} else {
}
});
}
搜索栏根本不会弹出位置。没有错误被抛出。也许问题来自带有角度 8 的 @ViewChild 的新版本。使用 Ionic 4 访问 DOM 也可能不同?
有什么想法可以帮助我吗?
亲切的问候