It’s effortless with Google Places API to add addresses in seconds against traditional inputs accepting Street Number, Street Name, City, State, Zip.
Google Autocomplete showed almost 20% time savings and error reduction on mobile. You save time by no longer dealing with incorrect addresses and the resulting problems.
There are multiple ways in Angular 2+ to implement google places API’s. Following steps shows how we can create a reusable component that can be used to autocomplete address.
Step 1: Install type/googlemaps
npm install --save @types/googlemaps
Steps 2: Add google API in index.html with own key.
To get API key follow instruction on
https://developers.google.com/maps/documentation/javascript/get-api-key
<script src=”https://maps.googleapis.com/maps/api/js?libraries=places&key=GOOGLE_KEY"></script>
Step 3: Create a component like google-places.component.ts
Step 4: Add new component to module.ts and use AutocompleteComponent with adressType input.
For Residential Address:
<AutocompleteComponent (setAddress)="getAddress($event)" adressType="geocode"></AutocompleteComponent>
For Office Address:
<AutocompleteComponent (setAddress)="getEstablishmentAddress($event)" adressType="establishment"></AutocompleteComponent>
On component file getAddress / getEstablishmentAddress method will emit place object which can be parsed to show on screen in required format.
...
getAddress(place: object) {
this.address = place[‘formatted_address’];
...
For complete code refer below GitHub source.
GitHub source: https://github.com/dhormale/google-places-autocomplete
If you found this useful, hit that 👏button :)
Reference:
Google Places API https://developers.google.com/places/web-service/intro
Google Places Supported Types: https://developers.google.com/places/supported_types
Google API Geo-coding restrictions: https://developers.google.com/maps/documentation/javascript/examples/geocoding-component-restriction