使用Angular为Google地方信息自动填充指定起始位置

jac*_*414 5 angular-google-maps angular

我正在使用AGM提供的带有Angular的Google Places Autocomplete API .它运行良好,但我无法手动设置我的起始位置.这意味着,如果我坐在洛杉矶的电脑前,我希望能够告诉API返回结果,就像我在波士顿一样.我相信这可以在谷歌的基础上根据他们的文档,但我还没有弄清楚如何在我正在使用的Angular组件中做到这一点.

任何人都有一个提示如何让这个工作?以下是我的组件的相关部分.谢谢!

  setGoogleMapsAutocomplete() {
    this.mapsAPILoader.load().then(() => {
      let autocomplete = new google.maps.places.Autocomplete(this.searchElementRef.nativeElement, {
        types: ["address"]
      });
      autocomplete.addListener("place_changed", () => {
        this.ngZone.run(() => {
          let place = autocomplete.getPlace();

          this.address = '';

          for (var i = 0; i < place.address_components.length; i++)
          {
            var addressType = place.address_components[i].types[0];

            if (this.hasOwnProperty(addressType)) {
              let nameLength = addressType == 'administrative_area_level_1' ? 'short_name' : 'long_name';

              this[addressType] = place.address_components[i][nameLength];
            }
          }
          this.error = false;
        });
      });
    });
  }
Run Code Online (Sandbox Code Playgroud)

Dmi*_*try 1

显然您一直在使用此示例中的代码https://brianflove.com/2016/10/18/angular-2-google-maps-places-autocomplete/

您是否尝试添加location键并将lat,lon其作为值传递给您作为第二个参数传递给google.maps.places.Autocomplete. 所以它应该是这样的:

    let autocomplete = new google.maps.places.Autocomplete(this.searchElementRef.nativeElement, {
        types: ["address"],
        radius: 50000,
        location: `${this.latitude}, ${this.longitude}`
    });
Run Code Online (Sandbox Code Playgroud)

我为你创建了一个 stackblitz 沙箱https://stackblitz.com/edit/angular-google-maps-demo-qwrngk

请随意尝试,但不要忘记更改 API 密钥,因为我的配额似乎已超出。

更新

您还需要设置radius要返回地点结果的范围。