Angular 应该能够直接使用 googlemaps api 而不会出现太多问题。
下面的代码使用@agm/core作为地图,但是自动完成只是使用基本的谷歌地图API。如果您仍然遇到问题,也许值得尝试以下一些方法:
- 明确设置谷歌地图版本。
- 确保包含地点库
- 确保正确设置 css,有时如果未设置 z-index 和位置,自动完成功能最终会被隐藏。
组件.html
<div class="map-container">
<agm-map [latitude]="lat" [longitude]="lng" [zoom]="zoom">
<agm-marker [latitude]="lat" [longitude]="lng"></agm-marker>
</agm-map>
</div>
<div id="pac-container">
<input #search id="pac-input" type="text" placeholder="Enter a location">
</div>
组件.ts
import { Component, OnInit, ElementRef, ViewChild, NgZone } from '@angular/core';
import { MapsAPILoader } from '@agm/core';
@Component({
selector: 'app-map',
templateUrl: './component.html',
styleUrls: ['./component.css']
})
export class MapComponent implements OnInit {
lat: string;
lng: string;
zoom = 1;
private geoCoder;
@ViewChild('search')
public searchElementRef: ElementRef;
constructor(
private mapsAPILoader: MapsAPILoader,
private ngZone: NgZone) { }
ngOnInit() {
//load Places Autocomplete
this.mapsAPILoader.load().then(() => {
this.geoCoder = new google.maps.Geocoder;
const autocomplete = new google.maps.places.Autocomplete(this.searchElementRef.nativeElement);
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.lat = place.geometry.location.lat();
this.lng = place.geometry.location.lng();
this.zoom = 12;
});
});
});
}
}
组件.css
.map-container {
bottom: 0px;
top: 0px;
left: 0px;
position: absolute;
right: 0px;
}
agm-map {
height: 100%;
width: 100%;
}
#pac-container {
padding-bottom: 12px;
margin-right: 12px;
z-index: 5000; /* not setting this can lead to angular hiding the autocomplete */
position: absolute; /* not setting this can lead to angular hiding the autocomplete */
}
您的应用程序模块需要正确导入@agm/core。
AgmCoreModule.forRoot({
apiKey: 'yourapikey',
libraries: ["places"],
apiVersion: 'quarterly'
}),