An Angular 2 component to fetch Geo-location
In order to get Geo-location from the browser we have to write custom SDK wrapping code each time we make HTML5 or Google API calls. While working on a project at TixDo we faced the same problem and the solution we developed, is ng2-location component.
ng2-location is an Angular 2 component for fetching current Geo-location. This component aims to provide a quick and easy way to consume Geo-location information made available by modern browsers in Angular 2 apps. Apart from this it also have a Injectable() service i.e EmitterService created to emit and receive the Geo location data in the form of a interface Location which is stored in the local storage.
How to use -
ng2-location component is a fully integrated and self-sustained component.
- Go to the link and download the zip package.
- Unzip this package and add the component “ng2-location” to your existing angular 2 app.
- To load ng2-location component use <ngLocation></ngLocation>
selector in view of any component, also don’t forget to import “ngSelectLocation” and “EmitterService” in that component. - Include EmitterService in providers and register ngSelectLocation in directives.
Example -
The following piece of code shows a working example of ng2-location component:
import {Component, OnInit} from ‘angular2/core’;
import {ngSelectLocation, EmitterService} from ‘./components/ng2-location/browser-location’;@Component({
selector: ‘seed-app’,
providers: [EmitterService],
directives: [ngSelectLocation],
template: `
<ngLocation></ngLocation>
`
})export class SeedApp implements OnInit{
public selectedCity:any;
constructor(private EmitterService: EmitterService) {
window.localStorage.removeItem(“city”);
}ngOnInit(){
this.selectedCity = localStorage.getItem(‘city’);
EmitterService.get(“selectedCity”).subscribe(data =>{
this.selectedCity = data;
localStorage.setItem(‘city’, data);
});
}
}
In our example we have also implemented ngOnInIt() life-cycle hook of angular 2 component to get the city name from local storage.