use*_*680 6 javascript google-maps google-maps-api-3 angular
我有一个 Angular 9(刚从 8 迁移),我需要使用 Google Places API(我有一个 API 密钥)进行地址自动完成,我可以用 @angular/googlemaps 库显示地图,但我不能自动完成工作...
我尝试使用https://developers.google.com/maps/documentation/javascript/examples/places-autocomplete代码,但我无法使 angular 使用 javascript... 或尝试使用@agm/coreand @angular-material-extensions/google-maps-autocomplete,也不工作...
我最好的办法是尽可能地使用它,但我不知道如何在 Angular 中只使用 javascript ......有一个像地图这样的角度原生组件?o 如何实现 Google 在演示中使用的 javascript 方式?
Angular 应该能够直接使用 googlemaps api,而不会出现太多问题。
下面的代码使用@agm/core 作为地图,但是自动完成只是使用基本的谷歌地图 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>
Run Code Online (Sandbox Code Playgroud)
组件.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;
});
});
});
}
}
Run Code Online (Sandbox Code Playgroud)
组件.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 */
}
Run Code Online (Sandbox Code Playgroud)
您的应用程序模块需要正确导入 @agm/core。
AgmCoreModule.forRoot({
apiKey: 'yourapikey',
libraries: ["places"],
apiVersion: 'quarterly'
}),
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
11812 次 |
| 最近记录: |