kuhnza / angular-google-places-autocomplete

Pure AngularJS directive for Google Places Autocomplete
MIT License
257 stars 189 forks source link

Show only the street (not street + city + state) #122

Closed LucaPrete closed 7 years ago

LucaPrete commented 7 years ago

Hello,

Thanks for this great plugin. Very useful and easy to use!

I'm using it in a form where I have different text inputs for street, city, state and country.

My question is, how can I get -for example- only the street part of the address?

For example, if in the street field the user looks for 1000 El Camino Real, I'd like to have this written in the input after the user selection, not 1000 El Camino Real, Menlo Park, California, United States. Of course, I'm ok if the full address comes out in between the suggestions, but not in the text input.

Any reply would be greatly appreciated!

Thanks again,

-Luca

LucaPrete commented 7 years ago

After working on this way more, I found the solution and I thought it was good for future reference to include it here for other people with the same issue.

I've noticed that the model was populated with a "complex" object, and not with a string. This allowed me to listen for select events of the component in my controller and set different fields (model) accordingly:

In the HTML I have

input g-places-autocomplete options="vm.autocompleteOptions" id="street" ng-model="vm.property.street" type="text" class="form-control" autocomplete="off" required autofocus>

and

<input id="zipcode" ng-model="vm.property.zipcode" type="text" value="20100" maxlength="5" class="form-control" required autofocus>

What I wanted to achieve was: as soon as a user selects the full address from the autocomplete (while typing an address), put the street address only in the street text input, and the related zipcode only in the zipcode text input.

Js (controller) Please note I use controllerAs and this instead of $scope only. I've also used lodash to retrieve the zipcode from the object.

// When a street is choosen from the google autocomplete options, set the street only // address in the street field of the form, and the zipcode in the zipcode field of // the form $scope.$on('g-places-autocomplete:select', (event, param) => { this.property.street = param.name; this.property.zipcode = _.find(param.address_components, function (o) { return o.types[0] === 'postal_code'; }).short_name; });

Hope it helps, since it took me a while to figure this out!

Thanks again for the great plugin, ciao!

-Luca