Reputation: 11
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
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
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