Autocomplete Google places in an input field on Angular 9 using Google Maps.

Here we are going to create an input field and integrate that field to Google Maps, to autocomplete a searched location without the use of any angular-maps package.

All we need to install is a type package for google.

Here is the screenshot of the app we are going to build.

Screenshot
Screenshot

Getting Started

Create a new angular app.

ng new google-map-tutorial

Go to the respective folder.

cd google-map-tutorial

For using google maps location and places, you need to create a Google Maps API key.
Refer this page to create a Maps API key.

Once you create an API key, include this in the index.html file as given below:

<script  src="https://maps.googleapis.com/maps/api/js?libraries=places&key=your_api_key"></script>

Then, add an input field in the app.component.html file for getting user input and also create a div tag to show a map with the selected location.

Add elementRef for both the tags to get the reference to perform logic.

app.component.html

<input  type="text" #addresstext>
<div #gmap style="width:600px;height:450px">
</div>

app.component.ts

@ViewChild('addresstext') addresstext:  ElementRef;
@ViewChild('gmap') gmapElement:  any;

Now add google types in angular by installing a package called @types/googlemaps.

npm i @types/googlemaps

And add  this line on the top of app.component.ts.

 /// <reference  types="@types/googlemaps"  />

We are going to initialize the autocomplete on AfterViewInit lifecycle hook by calling  function getPlaceAutocomplete().

ngAfterViewInit():  void {
	this.getPlaceAutocomplete();
}
getPlaceAutocomplete() {
	const autocomplete  =  new  google.maps.places.Autocomplete(this.addresstext.nativeElement,
	{
		componentRestrictions: { country:  'US' },
		types: ['establishment', 'geocode'] 

	});
	google.maps.event.addListener(autocomplete, 'place_changed', () => {
		const place  =  autocomplete.getPlace();
		console.log(place);
	});
}

The google.maps.places.Autocomplete inside getPlaceAutocomplete()  take  the reference of input field and some options for searching the maps as arguments.
Here I have restricted the maps search location to only US and types as 'establishment', 'geocode'.

interface  AutocompleteOptions {
	bounds?:  LatLngBounds  |  LatLngBoundsLiteral;
	componentRestrictions?:  ComponentRestrictions;
	placeIdOnly?:  boolean;
	strictBounds?:  boolean;
	types?:  string[];
	type?:  string;
	fields?:  string[];
}

These are the different options you can provide inside the options argument.

Refer Google Maps Autocomplete Docs for more information.

The google.maps.event.addListener will take the three arguments.
First one is the instance autocomplete, second the event name as 'place_changed'  and third is a callback function.

const  place = autocomplete.getPlace();

Will give the details of the selected location and is saved in a variable.

Info

At this point we will have an input field with autocomplete integrated and the place variable will hold all the pieces of information related to the selected location.

Show Map

To construct a map we need to create a map variable which needs the div elementRef  and  map options.

place.geometry.location will give Latitude and Longitude.

const  myLatlng  =  place.geometry.location;
const  mapOptions  = {
	zoom:  15,
	center:  myLatlng
};
const map  =  new google.maps.Map(this.gmapElement.nativeElement, mapOptions);

Refer this google maps document to know more about various Map Options

Add Marker

Add these code to create a marker.

   const  marker  =  new  google.maps.Marker({
		position:  myLatlng,
		title:  place.name
	});
	marker.setMap(map);

marker.setMap(map); will add the marker to the corresponding map.

Final Code

app.component.ts

/// <reference  types="@types/googlemaps"  />

import { Component, ElementRef, ViewChild, AfterViewInit } from  '@angular/core';

@Component({
	selector:  'app-root',
	templateUrl:  './app.component.html',
	styleUrls: ['./app.component.scss']
})
export  class  AppComponent  implements  AfterViewInit {
	@ViewChild('addresstext') addresstext:  ElementRef;
	@ViewChild('gmap') gmapElement:  any;
	
	ngAfterViewInit():  void {
		this.getPlaceAutocomplete();
	}
	getPlaceAutocomplete() {
		const  autocomplete  =  new  google.maps.places.Autocomplete(this.addresstext.nativeElement,
		{
			componentRestrictions: { country:  'US' },
			types: ['establishment', 'geocode'] 
		});

		google.maps.event.addListener(autocomplete, 'place_changed', () => {
			const  place  =  autocomplete.getPlace();
			const  myLatlng  =  place.geometry.location;
			const  mapOptions  = {
				zoom:  15,
				center:  myLatlng
			};
			const  map  =  new  google.maps.Map(this.gmapElement.nativeElement, mapOptions);
			const  marker  =  new  google.maps.Marker({
				position:  myLatlng,
				title:  place.name
			});
			marker.setMap(map);
		});
	}
}

app.component.html

<input  type="text" #addresstext>
<div #gmap style="width:600px;height:450px">
</div>
Subscribe to newsletter
Need more tech news? Tune in to our weekly newsletter to get the latest updates