Google Maps And Local Storage In Angular 2

In this tutorial, I am going to introduce how easy it is to integrate Google Maps in Angular. I am going to show you how you can plot markers on a map, add a new marker, and store it to the local storage.

So are you exited???

Yes, let’s start with the tutorial. First, I will show how to setup the configuration for Google Maps.

First of all, visit this URL to integrate Google Maps in Angular.


Then, click on "Getting Started" button and scroll down to setting up angular2-google-maps and write dependency to package.json

Npm install angular2-google-maps - -save

Then, run npm install from command prompt. You can also get your Google Mapa API key as shown in the below.




Then, after creating a new project or choosing existing project, press on enable API to get your Maps API key.


Okay. Now, we are all set to integrate Google Maps in our project. I am just copying the key i.e. just generated and paste it to app.module.ts file as shown below.


Now, I am plotting my hometown Ahmedabad on map. To do so, I am first statically creating two variables on app.component.ts naming them as "lat" and "lng" and then, I will bind them to html, as shown in below files.

app.component.ts

  1. import { Component } from '@angular/core';  
  2. @Component({  
  3.   selector: 'app-root',  
  4.   templateUrl: './app.component.html',  
  5.   styleUrls: ['./app.component.css']  
  6. })  
  7. export class AppComponent {  
  8.   lat: number = 23.022505;  
  9.   lng: number = 72.571362;  
  10. }   

app.component.html

  1. <div class="page-header">  
  2.   <h1>Google Map In Angular </h1>  
  3. </div>  
  4. <div class="container">  
  5. <div class="row">  
  6.   <div class="col-md-12">  
  7.     <div class="map">  
  8.       <sebm-google-map [latitude]="lat" [longitude]="lng">  
  9.         <sebm-google-map-marker [latitude]="lat" [longitude]="lng"></sebm-google-map-marker>  
  10.       </sebm-google-map>  
  11.     </div>  
  12.   </div>  
  13. </div>  
  14. </div>  

Isn’t it easy friends??? But again, it’s just a static one. Now, in next step, I will create an array of lat and lng and plot all the elements of array to map. So, let’s just do it.!!

To do it, I am first creating an interface named as marker to provide type that contains three variables-  name, lat, and lng.

  1. export interface marker{  
  2.     name?:string;  
  3.     lat:number;  
  4.     lng:number;  
  5. }   

Now, to keep my logic centralized, I am creating one service and naming it as markerdata.service.ts and inside the service, I am creating the array of markers and methods to return the array as shown below and as you know services must be provided in order to use them in projects. (i.e. service must be declared in providers array inside app.module.ts)

Markerdata.service.ts 

  1. import { Injectable } from '@angular/core';  
  2. import { marker } from './marker';  
  3. @Injectable()  
  4. export class MarkerdataService {  
  5.   markers: marker[] = [  
  6.     {  
  7.       name: 'Ahmedabad',  
  8.       lat: 23.022505,  
  9.       lng: 72.571362  
  10.     },  
  11.     {  
  12.       name: 'Baroda',  
  13.       lat: 22.307159,  
  14.       lng: 73.181219  
  15.     },  
  16.     {  
  17.       name: 'Surat',  
  18.       lat: 21.170240,  
  19.       lng: 72.831061  
  20.     },  
  21.     {  
  22.       name: 'Rajkot',  
  23.       lat: 22.303894,  
  24.       lng: 70.802160  
  25.     },  
  26.   ];  
  27.   constructor() { }  
  28.   getAllMarkers() {  
  29.     if (localStorage.getItem('markers') === null || localStorage.getItem('markers') === undefined) {  
  30.       localStorage.setItem('markers', JSON.stringify(this.markers));  
  31.       return this.markers;  
  32.     }  
  33.     else {  
  34.       var markers = JSON.parse(localStorage.getItem('markers'));  
  35.       return markers;  
  36.     }  
  37.   
  38.   }  
  39.   addMarker(newmarker: marker) {  
  40.   
  41.     var markers = JSON.parse(localStorage.getItem('markers'));  
  42.     markers.push(newmarker);  
  43.     localStorage.setItem('markers', JSON.stringify(markers));  
  44.   }  
  45.   removeMarker(mark: marker) {  
  46.   
  47.     var markers = JSON.parse(localStorage.getItem('markers'));  
  48.     markers.splice(markers.indexOf(mark),1);  
  49.     localStorage.setItem('markers', JSON.stringify(markers));  
  50.   }  
  51. }   

Here, in the above code, I have created methods for addMarker, removeMarker, and getAllMarker. And, I am also using local storage to preserve the values.

In getAllMarker method, I am first checking if the local storage has a value for key “markers;” if yes then load values from that key and if no then load the values from array and set the local storage.

In addMarker method, I am first fetching all the markers in markers and then adding newmarker to the markers and again setting the local storage with markers. Same for removeMarker, but in removeMarker I am splicing the marker from the array instead of pushing..

So, all done to fetch the markers!!

app.component.ts 

  1. import { Component } from '@angular/core';  
  2. import { marker } from './marker';  
  3. import { MarkerdataService } from './markerdata.service';  
  4. @Component({  
  5.   selector: 'app-root',  
  6.   templateUrl: './app.component.html',  
  7.   styleUrls: ['./app.component.css']  
  8. })  
  9. export class AppComponent {  
  10.   lat: number = 23.022505;  
  11.   lng: number = 72.571362;  
  12.   allMarkers: marker[];  
  13.   constructor(private _data: MarkerdataService) {  
  14.     this.allMarkers = this._data.getAllMarkers();  
  15.   }  
  16.   onClick(m: any) {  
  17.     console.log(m);  
  18.   }  
  19.   onMapClicked($event) {  
  20.     var newMarker:marker={  
  21.       name:'No Name',  
  22.       lat:$event.coords.lat,  
  23.       lng:$event.coords.lng  
  24.     }  
  25.     console.log(newMarker);  
  26.     this.allMarkers.push(newMarker);  
  27.     this._data.addMarker(newMarker);  
  28.   }  
  29.   onDelete(m:marker)  
  30.   {  
  31.     this.allMarkers.splice(this.allMarkers.indexOf(m),1);  
  32.     this._data.removeMarker(m);  
  33.   }  
  34. }   

app.component.html

  1. <div class="page-header">  
  2.   <h1>Google Map In Angular </h1>  
  3. </div>  
  4. <div class="container">  
  5.   <div class="row">  
  6.     <div class="col-md-12">  
  7.       <div class="map">  
  8.         <sebm-google-map (mapClick)="onMapClicked($event)" [latitude]="lat" [longitude]="lng">  
  9.           <sebm-google-map-marker   
  10.           *ngFor="let m of allMarkers"  
  11.           (markerClick)="onClick(m)"  
  12.           [latitude]="m.lat"   
  13.           [longitude]="m.lng"   
  14.           >  
  15.               <sebm-google-map-info-window>  
  16.                 <strong>{{m.name}}</strong>  
  17.                 <br>  
  18.                 <a class="delete" (click)="onDelete(m)">Delete</a>  
  19.               </sebm-google-map-info-window>  
  20.           </sebm-google-map-marker>  
  21.         </sebm-google-map>  
  22.       </div>  
  23.     </div>  
  24.   </div>  
  25. </div>   

Now let me first explain the html portion of above code

<sebm-google-map> is to display the map.

<sebm-google-map-marker> is to plot the markers so I looped through my allMarkers array inside this tag.

<sebm-google-map-info-window> is to display basic information of particular marker.

And there is many more available in documents which is available here.

Here, in the above code, I have created the following events

  1. (mapClick)="onMapClicked($event)"
    This event is for adding a new marker (i.e. if I will clicked on any empty places on map it will simple plot marker there with name = No Name.)
  1. (markerClick)="onClick(m)"
    This event is for display info about the clicked marker.(i.e. it will display the name)
  1. (click)="onDelete(m)"
    This event is to delete the particular marker.

Output




Summary

SourceCode

So, in this tutorial, you learned how to integrate Google Maps with Angular and also, how to use local storage for storing the markers.

Thanks for reading and I hope it will be helpful to you.