2017-08-10 23 views
1

我想在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)); 
     }; 
} 
+0

工作,如果我刪除窗口嘗試與navigator.geolocation它不會工作? –

回答

1

是:

navigator.geolocation.getCurrentPosition() 

下面是一個小例子,使用打字稿:

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

試試這個,這對我來說

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); 
    } 
    } 
    }); 
    });  
    };