Share with   

Add auto search google map places or location search bar into angular app

Here we use google auto search find location or places using search bar and display location marker into google map in angular application.


Google Auto Find Location or Place Search Bar

Google map is used to search location or places. Here we are going to add google map into angular framework for integrate google map in application. Using auto search google places bar we are finding location or place and select location to add marker into google map.

 

Prerequisite

  1.    Install Node JS.

  2.    Install Angular CLI

  3.    Install Bootstrap 4.

  4.    Install Google Maps i.e. @Agm/Core. to add google map using article click here.

 

Example for Add Location/ Places Search Bar

Into previous article we are learn how to add google map into angular app. If you do not see how we implement google map into angular app. Please read this article.

Add google maps with add marker getting current location using @agm/core module in angular framework.

Follow this article to install google map and integrate simple google map into your angular app.

In Previous tutorial we seen google map template using getting current location into angular app like this

 

HTML Code

// src > app > app.component.html

<div class="googlemap"><!-- app.component.html --><agm-map [latitude]="latitude" [longitude]="longitude" [zoom]="zoom"><agm-marker [latitude]="latitude" [longitude]="longitude"></agm-marker></agm-map>
</div>

CSS Code

// src > app > app.component.css

agm-map {
   height: 500px;
}

.googlemap{
   margin-top: 5%;
}

TS Code

import { Component, OnInit } from "@angular/core";
@Component({
 selector: "app-root",
 templateUrl: "./app.component.html",
 styleUrls: ["./app.component.css"]
})
export class AppComponent implements OnInit {

 title: string = 'Google Map Project';
 latitude: number;
 longitude: number;
 zoom:number;

 ngOnInit() {
   this.setCurrentLocation();
 }
   // Get Current Location Coordinates
   private setCurrentLocation() {
     if ('geolocation' in navigator) {
       navigator.geolocation.getCurrentPosition((position) => {
         this.latitude = position.coords.latitude;
         this.longitude = position.coords.longitude;
         this.zoom = 15;
       });
     }
   }
}

This will helps you to set marker into google map to your current location.

 

Now we add location or place search bar to search place by adding first keyword.

1) Install GoogleMaps types library

npm install @types/googlemaps --save-dev

 

2) Add googlemaps in types array list into tsconfig.app.json file already available into at the project directory

// projectname < tsconfig.app.json

{
 "extends": "../tsconfig.json",
 "compilerOptions": {
   "outDir": "../out-tsc/app",
   "types": [
     "googlemaps"
   ]
 },
 "exclude": [
   "test.ts",
   "**/*.spec.ts"
 ]
}

 

3) You need to activate some services in google api i.e. Maps JavaScript API (Show Map), Places API (Places search results) & Geocoding API (Convert Lat & Long to address)

 

4) Now add search bar to HTML file

// src > app > app.component.html

<!-- app.component.html -->
<div class="googlemap container">
 <h1>Angular Google Maps with Places Search Example</h1>
 <div class="form-group">
   <label>Enter address</label>
   <input type="text" class="form-control" (keydown.enter)="$event.preventDefault()"
     placeholder="Search Nearest Location" autocorrect="off" autocapitalize="off" spellcheck="off" type="text" #search>
 </div>

 <agm-map [latitude]="latitude" [longitude]="longitude" [zoom]="zoom">
   <agm-marker [latitude]="latitude" [longitude]="longitude" [markerDraggable]="true"
     (dragEnd)="markerDragEnd($event)"></agm-marker>
 </agm-map>

 <br>
 <h5>Address: {{address}}</h5>
 <div>Latitude: {{latitude}}</div>
 <div>Longitude: {{longitude}}</div>
</div>

#search is autocomplete google place search bar activate api

keydown.enter is used to get keys when pressed so #search will send this keyword to google place search api to find location

 

5) Add the TS code into component.ts file

import { Component, OnInit, ViewChild, ElementRef, NgZone } from "@angular/core";
import { MouseEvent, MapsAPILoader } from '@agm/core';

@Component({
 selector: "app-root",
 templateUrl: "./app.component.html",
 styleUrls: ["./app.component.css"]
})
export class AppComponent implements OnInit {

 title: string = 'Google Map Project';
 latitude: number;
 longitude: number;
 zoom: number;
 address: string;
 private geoCoder;

 @ViewChild('search',{static: false})
 public searchElementRef: ElementRef;

 constructor(
   private mapsAPILoader: MapsAPILoader,
   private ngZone: NgZone
 ) { }

 ngOnInit() {
   //load Places Autocomplete
   this.mapsAPILoader.load().then(() => {
     this.setCurrentLocation();
     this.geoCoder = new google.maps.Geocoder;

     let autocomplete = new google.maps.places.Autocomplete(this.searchElementRef.nativeElement, {
       types: ["address"]
     });
     autocomplete.addListener("place_changed", () => {
       this.ngZone.run(() => {
         //get the place result
         let place: google.maps.places.PlaceResult = autocomplete.getPlace();

         //verify result
         if (place.geometry === undefined || place.geometry === null) {
           return;
         }

         //set latitude, longitude and zoom
         this.latitude = place.geometry.location.lat();
         this.longitude = place.geometry.location.lng();
         this.zoom = 12;
       });
     });
   });
 }

 // Get Current Location Coordinates
 private setCurrentLocation() {
   if ('geolocation' in navigator) {
     navigator.geolocation.getCurrentPosition((position) => {
       this.latitude = position.coords.latitude;
       this.longitude = position.coords.longitude;
       this.zoom = 8;
       this.getAddress(this.latitude, this.longitude);
     });
   }
 }

 markerDragEnd($event: MouseEvent) {
   console.log($event);
   this.latitude = $event.coords.lat;
   this.longitude = $event.coords.lng;
   this.getAddress(this.latitude, this.longitude);
 }

 getAddress(latitude, longitude) {
   this.geoCoder.geocode({ 'location': { lat: latitude, lng: longitude } }, (results, status) => {
     console.log(results);
     console.log(status);
     if (status === 'OK') {
       if (results[0]) {
         this.zoom = 12;
         this.address = results[0].formatted_address;
       } else {
         window.alert('No results found');
       }
     } else {
       window.alert('Geocoder failed due to: ' + status);
     }
   });
 }
}

This code will activate the google auto search api to get the list synchronously when you add the keyword.

 

Author Image
Guest User

0 Comments