我们如何获得angular2打字稿的地理位置?
问题描述:
我想在angular2上获取地理位置,但目前为止还不可能。 请检查我尝试过的代码。我们如何获得angular2打字稿的地理位置?
location = {};
setPosition(position){
this.location = position.coords;
console.log(position.coords);
}
ngOnInit(){
if(window.navigator.geolocation){
window.navigator.geolocation.getCurrentPosition(this.setPosition.bind(this));
};
}
答
是:
navigator.geolocation.getCurrentPosition()
下面是一个小例子,使用打字稿:
navigator.geolocation.getCurrentPosition(position => {
console.log(position);
// in your case
this.location = position.coords;
});
答
试试这个,这对我来说
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);
}
}
});
});
};
工作,如果我删除窗口尝试与navigator.geolocation它不会工作? –