2017-10-23 12 views
0

私はループしているfirebaseのアイテムが複数あり、それらの名前はcategoryId、lat、lonです。Firebase AngularJS array map()

2 lat、lon(1つがfirebaseのもの)からの距離を計算しようとしています。もう1つはユーザーの場所です。

これはすべて問題ありません。それも問題なく計算できます。しかし、新しい変数を私が購読しているfirebase配列に注入/マップするにはどうしたらいいですか?

this.categoryId = this.navParams.get('categoryId'); 
afoDatabase.list('/list', {query: { 
    orderByChild: "categoryId", 
    equalTo: parseInt(this.categoryId) 
}}).subscribe(listItems => { 
    this.items = listItems; //need to add distance within array 
    loadingPopup.dismiss().catch(() => {}); 
}); 

たとえば、私はすべてを計算し値を持つdistanceという変数を持っています。これをこのアイテムにどのように追加すればよいのですか?HTML側から呼び出せますか?助けのための

感謝:)

答えて

0

(例えばthis.distance)最初の関数を作成し、変数を作成し、注入し、この変数にあなたの関数の値を取得します。その後、長さに基づいて増分するforループを使用し、それぞれに追加するにはthis.items[i]["distance"]を使用します。たとえば、次のように

this.categoryId = this.navParams.get('categoryId'); 
    afoDatabase.list('/list', {query: { 
     orderByChild: "categoryId", 
     equalTo: parseInt(this.categoryId) 
    }}).subscribe(listItems => { 
     this.items = listItems; 

     this.geolocation.getCurrentPosition({timeout:15000}).then((resp) => { 

     this.myLat = resp.coords.latitude; 
     this.myLong = resp.coords.longitude; 


     }).catch((error) => { 
      console.log('Error getting location', error); 
     }); 



     for (var i = 0, len = this.items.length; i < len; i++) { 
      this.distance = this.calculateDistance(this.myLat, this.myLong, this.items[i].lat, this.items[i].lng); 
      this.items[i]["distance"] = Math.round(this.distance); 
       console.log('testing myLat', this.myLat) 
       console.log('testing myLong', this.myLong) 
      } 

      console.log('testing inject', this.items) 
     loadingPopup.dismiss().catch(() => {}); 
    }); 

機能

calculateDistance(lat1:number,lon1:number,lat2:number,lon2:number){ 

    let R = 6371; // km 
    let dLat = (lat2 - lat1) * Math.PI/180; 
    let dLon = (lon2 - lon1) * Math.PI/180; 
    let a = Math.sin(dLat/2) * Math.sin(dLat/2) + 
        Math.cos(lat1 * Math.PI/180) * Math.cos(lat2 * Math.PI/180) * 
        Math.sin(dLon/2) * Math.sin(dLon/2); 
    let c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a)); 
    let d = R * c; 
    return d; 
} 
関連する問題