Angular 9 Google 地图 API 地点自动完成

2024-01-03

我有一个 Angular 9(刚刚从 8 迁移),我需要使用 Google Places API(我有一个 API 密钥)进行地址自动完成,我可以使用 @angular/googlemaps 库显示地图,但我无法制作自动完成工作...

我尝试使用https://developers.google.com/maps/documentation/javascript/examples/places-autocomplete https://developers.google.com/maps/documentation/javascript/examples/places-autocomplete代码,但我无法使角度使用 javascript...或尝试使用@agm/core and @angular-material-extensions/google-maps-autocomplete,也没有工作...

我最好的选择是尽可能原生地使用它,但我不知道如何在 Angular 中仅使用 javascript...有像地图这样的 Angular 原生组件吗? o 如何实现 Google 在演示中使用的 javascript 方式?


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'
}),
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Angular 9 Google 地图 API 地点自动完成 的相关文章