ArunKumar Umma
ArunKumar Umma

Reputation: 11

how can we get geo location in angular2 typescript?

I am trying to get geolocation on angular2,but it is impossible so far. Please check the code i have tried.

location = {};
  setPosition(position){
  this.location = position.coords;
  console.log(position.coords);
  }

     ngOnInit(){
        if(window.navigator.geolocation){
          window.navigator.geolocation.getCurrentPosition(this.setPosition.bind(this));
      };
}

Upvotes: 1

Views: 1948

Answers (2)

MonsieurMan
MonsieurMan

Reputation: 340

It is:

navigator.geolocation.getCurrentPosition()

Here is a minimal example using typescript :

navigator.geolocation.getCurrentPosition(position => {  
    console.log(position);  
    // in your case
    this.location = position.coords;
});

Upvotes: 1

Girija
Girija

Reputation: 109

Try this,It's worked for me

 if(navigator.geolocation){
    navigator.geolocation.getCurrentPosition(position => {
        this.lat=position.coords.latitude;
        this.long=position.coords.longitude;
        var latlng = { lat: this.lat, lng:this.long };

       let geocoder = new google.maps.Geocoder();
     geocoder.geocode(  {'location':latlng}, (results, status) => {
     if (status == google.maps.GeocoderStatus.OK) {
     let result = results[0];
     let rsltAdrComponent = result.address_components;
     let resultLength = rsltAdrComponent.length;
     if (result != null) {
     console.log(rsltAdrComponent[resultLength-5].short_name)
     } else {
     window.alert('Geocoder failed due to: ' + status);
     }
     }
     });
     });     
   };

Upvotes: 0

Related Questions