Angular 9谷歌地图API放置自动完成



我有一个Angular 9(刚刚从8迁移过来(,我需要使用Google Places API(我有API键(来完成地址自动完成,我可以用@Angular/googlemaps库显示地图,但我无法使自动完成工作。。。

我试着用https://developers.google.com/maps/documentation/javascript/examples/places-autocomplete代码,但我无法使angular使用javascript。。。或者尝试使用@agm/core@angular-material-extensions/google-maps-autocomplete,也不起作用。。。

我的最佳选择是尽可能使用它的原生版本,但我不知道如何在Angular中只使用javascript。。。有一个像地图一样的角度原生组件吗?o如何实现Google在演示中使用的javascript方式?

Angular应该能够直接使用谷歌地图api,而不会出现太多问题。

下面的代码使用@agm/core作为地图,但是自动完成只是使用基本的谷歌地图api。如果你仍然有问题,也许值得尝试以下方法:

  • 显式设置谷歌地图版本
  • 确保包括地点图书馆
  • 确保它设置的css正确,有时如果没有设置z索引和位置,自动完成会被隐藏

component.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;
}); 
});
});
}
}

component.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'
}),

您可以使用此库https://github.com/angular-material-extensions/google-maps-autocomplete.

我发布了一个用于angular 8+(已测试(应用程序的小角度指令。如果你不想使用谷歌提供的默认下拉列表,它以编程方式包装了googleplace API,以提供完整的集成。它还处理";输入";键自动选择下拉列表的第一个结果。

您可以在这里查看演示:https://github.com/vlafranca/ngxAutocomPlace在此处安装npm:https://www.npmjs.com/package/ngx-autocom-place

最新更新