Angular – Display Current Location Using Google Map

Published Jan 11, 2018
Angular – Display Current Location Using Google Map

Photo by rawpixel.com on Unsplash

In this blog post, I’m going to show you how to display your current location with google map. I’m going to use Angular Google Maps ( AGM ) to speed up the development time and it is also very easy to use. It is also a nice way for me to try out libraries in Angular ecosystem.

Set up

To add the library to your project, open a command prompt and run this command

npm install @agm/core --save

And add the necessary imports to your app.module.ts

// imagine more imports here
import { AgmCoreModule } from '@agm/core'; 
@NgModule({
  imports: [
    //imagine modules here
    AgmCoreModule.forRoot({
      apiKey: 'YOUR_KEY'
    })
  ],
  providers: [],
  declarations: [ AppComponent ],
  bootstrap: [ AppComponent ]
})
export class AppModule {}

Getting API Key

  1. Go to the Google API Console.
  2. Select a project or create a new one. Note that if you are a Firebase user, you can see your project here and use it for getting an API key.

Replace the placeholder key in the app.module.ts with your own key.

We’re done with the setup.

Now we can use the agm like this

<agm-map [latitude]="lat" [longitude]="lng"> 
  <agm-marker [latitude]="lat" [longitude]="lng">
   </agm-marker> 
</agm-map>

To mark our current location, we are mainly interested in “latitude” and longitude” inputs.

All we have left to do is get those values. We can get those values with the code snippet below.

import { Component } from '@angular/core';
import {HttpClient} from '@angular/common/http';
@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  name = 'Angular 5';
  lat:any;
  lng:any;
  constructor(){
    if (navigator)
    {
    navigator.geolocation.getCurrentPosition( pos => {
        this.lng = +pos.coords.longitude;
        this.lat = +pos.coords.latitude;
      });
    }
  }
}

That’s it. Thanks for reading.

Here’s the stackblitz demo

Discover and read more posts from Brian
get started