簡體   English   中英

如何在GeocoderService中存儲來自geocoder.geocode()的地址並將其返回給app.component?

[英]How to store address from geocoder.geocode() in GeocoderService and return it to app.component?

我對angular和TypeScript真的很陌生,我正在開發使用google地圖查找地址的應用程序,而我無法從geocoder.geocode()存儲地址。

我從這里嘗試了解決方案: 如何從Google Maps JavaScript geocoder回調返回變量?

沒關系,alert()可以正常工作,但是我想要做的是將地址從GeocoderService傳遞到父組件並將其存儲在其中。 我試圖將其存儲在服務本身中,但是我不能!

GeocoderService:

initialize() {
    this.geocoder = new google.maps.Geocoder();
    var latlng = new google.maps.LatLng(40.730885,-73.997383);
    this.codeLatLng(function(addr){
      this.loc = addr; // <= here i can't store address it is undefined
      alert(addr);
      return this.loc;
    });

  }

  codeLatLng(callback) {
    var latlng = new google.maps.LatLng(40.730885,-73.997383);
    if (this.geocoder) {
      this.geocoder.geocode({'location': latlng}, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
          if (results[1]) {
            callback(results[1].formatted_address);
          } else {
            alert("No results found");
          }
        } else {
          alert("Geocoder failed due to: " + status);
        }
      });
    }
  }

app.component:

 constructor( private geolocationService: GeolocationService,
    private geocoderService: GeocoderService){
    this.position = {latitude: 0, longitude: 0}
    this.LatLng = new google.maps.LatLng( this.position.latitude, this.position.longitude);
  }

findMe(){
    this.geolocationService.getPosition().then((position: any) => {
      this.position = {latitude:position.coords.latitude,longitude: position.coords.longitude}
      this.LatLng = new google.maps.LatLng( this.position.latitude, this.position.longitude);
      this.map.setCenter(this.LatLng);
      this.loc = this.geocoderService.initialize(); //<= here i need this address to be returned and stored
      console.log(this.loc) // <= undefined
    })
 }

app.component.html:

<div #map style= "width:100%;height:400px"></div>
<button (click) = "findMe()">Find me</button>

如果問題愚蠢,請幫忙,抱歉

1)

   function(addr){
          this.loc = addr; // <= here i can't store address it is undefined
          alert(addr);
          return this.loc;
        }

此函數是一個回調函數,因此您無法從回調函數返回數據之所以擁有未定義的loc變量,是因為該應用程序組件類的“ This”已被該函數的“ This”遮蓋了,因此您可以解決此問題必須使用箭頭功能(但不能解決您的問題)

this.codeLatLng(addr=> this.loc = addr);

2)

  this.loc = this.geocoderService.initialize(); 

您將永遠不會獲得值,因為初始化不會返回值

3)所以你要做

由於codeLatLng的結果是異步的,請嘗試使用Subject或Observable對象,並在應用程序組件中將此對象替換為

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM