使用Angular为Google Places自动完成指定起始位置

时间:2019-01-29 23:03:39

标签: angular angular-google-maps

我正在使用AGM提供的带有Angular的Google Places Autocomplete API。效果很好,但我无法手动设置起始位置。意思是,如果我坐在洛杉矶的计算机上,我希望能够告诉API就像在波士顿一样返回结果。我相信基于their documentation,这在Google端是可能的,但是我还没有弄清楚如何在我使用的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;
        });
      });
    });
  }

1 个答案:

答案 0 :(得分: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}`
    });

我已经为您https://stackblitz.com/edit/angular-google-maps-demo-qwrngk

创建了一个stackblitz沙箱

可以随意使用,但不要忘记更改API密钥,因为似乎超出了我的配额。

更新

还需要设置radius,您要在其中返回位置结果。

相关问题