X
    Categories: Angularjs 2

Google map integration in Angular 2 with typescript

Google map integration in Angular 2 with typescript

Google map have a javascript api to build map in our code. Let us build a google map with angular 2 app. Here we have a package called angular2-google-maps which is developed by Sebastian Muller. Before install angular 2 you should have Node and NPM in you system. Here you can find a tutorial to install angular 2 .

angular2-google-maps works well with latest version of Node and NPM. So make sure you have a latest version of npm.

To check npm version run below command in terminal

npm -v

If you have an old version run below commands to install latest one.

npm install -g n
n latest

 

 

Step 1 :

Install angular 2 app [ Tutorial @ http://www.17educations.com/angularjs-2/install-angularjs-2/ ]

Step 2: Install  angular2-google-maps package

npm install angular2-google-maps --save

It will angular2-google-maps package at node_modules folder

Step 3: Edit you systemjs.config.js to map package with your app

Map package path to your app by placing path under map.

map: {
      // our app is within the app folder
      app: 'app',
      .............,
      .............,
      .............,
      .............,
       'angular2-google-maps/core': 'npm:angular2-google-maps/core/core.umd.js'
      },

Otherwise you will face the following error at console.
domain.com/angular2-google-maps/core Failed to load resource: the server responded with a status of 404 (Not Found)

Step 4: Modify app.modules.ts

My app.modules.ts

import { NgModule }      from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AgmCoreModule } from "angular2-google-maps/core";
import { FormControl, FormsModule, ReactiveFormsModule } from "@angular/forms";

import { AppComponent }  from './app.component';

@NgModule({
  imports:      [ 
  		AgmCoreModule.forRoot({
     		 	apiKey: "*********************",
     		 	libraries: ["places"]
    			}),
  		BrowserModule,
  		FormsModule,
  		ReactiveFormsModule
  		],
  declarations: [ AppComponent ],
  bootstrap:    [ AppComponent ]
})
export class AppModule { }

import AgmCoreModule from “angular2-google-maps/core”. AgmCoreModule which is an base class for angular2-google-maps core.
Write libraries under AgmCoreModule.forRoot({ ….. }) at @NgModule => imports. Enter your google map api key and declare libraries.

Step 5: Create template at you app.component.ts

My app.component.ts

import { Component, NgModule, NgZone, OnInit, ViewChild, ElementRef } from '@angular/core';
import { FormControl, FormsModule, ReactiveFormsModule } from "@angular/forms";
import { BrowserModule } from "@angular/platform-browser";
import { AgmCoreModule, MapsAPILoader } from 'angular2-google-maps/core';

@Component({
  selector: 'my-app',
  styles: [`
    .sebm-google-map-container {
       height: 300px;
     },
     
  `],
  template: `
    <div class="container">
      <h1>Angular 2 Integrate  Google Maps Places Autocomplete</h1>
      <div class="form-group">
        <input placeholder="search for location" autocorrect="off" autocapitalize="off" spellcheck="off" type="text" class="form-control" #search [formControl]="searchControl">
      </div>
      <sebm-google-map [latitude]="latitude" [longitude]="longitude" [scrollwheel]="false" [zoom]="zoom">
        <sebm-google-map-marker [latitude]="latitude" [longitude]="longitude"></sebm-google-map-marker>
      </sebm-google-map>
    </div>
  `
})
export class AppComponent implements OnInit {
}

Step 6 : Implement Map Code at your component [app.component.ts]

export class AppComponent implements OnInit {
  
  public latitude: number;
  public longitude: number;
  public searchControl: FormControl;
  public zoom: number;
  
  @ViewChild("search")
  public searchElementRef: ElementRef;
  
  constructor(
    private mapsAPILoader: MapsAPILoader,
    private ngZone: NgZone
  ) {}
  
  ngOnInit() {
    //set google maps defaults
    this.zoom = 4;
    this.latitude = 39.8282;
    this.longitude = -98.5795;
    
    //create search FormControl
    this.searchControl = new FormControl();
    
    //set current position
    this.setCurrentPosition();
    
    //load Places Autocomplete
    this.mapsAPILoader.load().then(() => {
      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;
        });
      });
    });
  }
  
  private setCurrentPosition() {
    if ("geolocation" in navigator) {
      navigator.geolocation.getCurrentPosition((position) => {
        this.latitude = position.coords.latitude;
        this.longitude = position.coords.longitude;
        this.zoom = 12;
      });
    }
  }
}

Import required libraries first. NgModule, NgZone, OnInit, ViewChild, ElementRef , FormsModule and MapsAPILoader
Declare public variables like latitude, longitude, searchControl and zoom

latitude, longitude and zoom are the variables which is used in <sebm-google-map> tag.

@ViewChild() will act as a DOM. It will used to get the Input element.
@ViewChild(“search”) => It will find #search in form and will get the value of it.
public searchElementRef: ElementRef => user defined variable searchElementRef which is an ElementRef to the search input.

MapsAPILoader => which will load the Google Map api with the places.

NgZone => It will enable us to perform asynchronous operations outside of the Angular zone.

ngOnInit() => It will execute the function on the time of page init. Here we will get the current position of map and fetch the location and place it to our map.

Step 7 : My index.html

<!DOCTYPE html>
<html>
  <head>
    <title>Angular QuickStart</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="styles.css">

    <!-- Polyfill(s) for older browsers -->
    <script src="node_modules/core-js/client/shim.min.js"></script>

    <script src="node_modules/zone.js/dist/zone.js"></script>
    <script src="node_modules/systemjs/dist/system.src.js"></script>

    <script src="systemjs.config.js"></script>
    <script>
      System.import('app').catch(function(err){ console.error(err); });
    </script>
  </head>

  <body>
    <my-app>Loading AppComponent content here ...</my-app>
  </body>
</html>

Step 8 : Run you code. now you can see google map at your code.

 

 

Hope it will help someone.
If you like this article don’t forget to share and comment.
Thanks!.

Marimuthu:

View Comments

  • Thanks for the tutorial, works well. How would you implement the reverse? As in the user drags the marker to a different spot and the input is filled in w/ the address of the marker position. Would you need geolocation service?