我有一个 Angular 9(刚从 8 迁移而来),我需要使用 Google Places API(我有一个 API key )来自动完成地址,我可以使用 @angular/googlemaps 库显示 map ,但我无法制作自动完成工作...
我尝试使用 https://developers.google.com/maps/documentation/javascript/examples/places-autocomplete代码,但我无法使用 javascript... 或尝试使用 @agm/core
和 @angular-material-extensions/google-maps-autocomplete
,也不工作...
我最好的选择是尽可能地使用它作为原生,但我不知道如何在 Angular 中只使用 javascript ......有像 map 这样的 Angular 原生组件吗? o 如何实现 Google 在演示中使用的 javascript 方式?
最佳答案
Angular 应该能够直接使用 googlemaps api 而不会出现太多问题。
下面的代码使用 @agm/core 作为 map ,但是自动完成只是使用基本的谷歌地图 api。如果您仍然有问题,可能值得尝试以下一些方法:
组件.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'
}),
关于javascript - Angular 9 Google Maps API Place Autocomplete,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61442561/