Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Specifying Starting Location For Google Places Autocomplete with Angular

I'm using the Google Places Autocomplete API with Angular provided by AGM. It works great, but I'm having trouble setting my starting location manually. Meaning, if I'm sitting at my computer in Los Angeles, I would like the ability to tell the API to return results as if I were in Boston. I believe this is possible on Google's end, based on their documentation, but I've yet to figure out how to do it within the Angular component I'm using.

Anyone have a tip for how to get this to work? Below is the relevant section of my component. Thanks!

  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;
        });
      });
    });
  }
like image 254
jackel414 Avatar asked Nov 06 '22 21:11

jackel414


1 Answers

Apparently you've been using code from this example https://brianflove.com/2016/10/18/angular-2-google-maps-places-autocomplete/

Have you tried to add location key and pass lat,lon as value to the object you're passing as a second argument to google.maps.places.Autocomplete. So it should be like:

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

I've created a stackblitz sandbox for you https://stackblitz.com/edit/angular-google-maps-demo-qwrngk

Feel free to play around, but don't forget to change the API key, because mine quota is seems to be exceeded.

UPDATE

You need also set the radius within which you want to return place results.

like image 118
Dmitry Avatar answered Nov 15 '22 07:11

Dmitry