2016-02-02 24 views
2

我有一些具有以下結構的位置數據。您如何使用.push或設置爲在Firebase中創建新的子密鑰?

[business: 
    Joes Pizza:{ 
accountid:1818 
address:32, Angle des Rue des Nimes et Blvd. Toussaint Louverture, 
city:Anytown 
country:USA 
created:At10/26/2015 7:27:42 PM 
heading: Fast Food 
headingid: 178 
latitude: 18.572203 
longitude:-72.306747 
name: Joes Pizza 
objectId:x9VRotBU2O 
phonenumber:1 509 473 6003 
website:http://pizza.com 
    }, 
] 

我想通過閱讀不同的緯度和長期信息和使用push()寫含有密鑰的latLng對象重新格式化爲擁有這一切商家地理編碼信息。

我能夠創建對象並將其記錄到控制檯,但是當我嘗試調用業務對象上的對象時,它的未定義。我在Firebase文檔中通過set()push()嘗試了此操作。

我試過以下版本以及fb.child('latLng').push({lat: snapshot.val().latitude, lng: snapshot.val().longitude});。無法實現。

<!doctype html> 
<html> 
<head> 
<script src="https://cdn.firebase.com/js/client/2.4.0/firebase.js"></script> 

</head> 
<body> 
<p>Geoloc</p> 
<script> 
var fb = new Firebase("https://crackling-fire.firebaseio.com/business"); 

// Retrieve relevant data 
fb.on("child_added", function(snapshot) { 
    var place = snapshot.val(); 
    var latLng = {lat: snapshot.val().latitude, lng: snapshot.val().longitude} 
    if (place.hasOwnProperty('longitude') && place.hasOwnProperty('latitude')) 
    { 

    fb.child('latLng').push(place.latLng); 

    console.log(place.name, place.latLng); 
    console.log(latLng); 
    }; 
    }, function (errorObject) { 
    console.log("The read failed: " + errorObject.code); 
}); 
</script> 
</body> 
</html> 

回答

1

有兩個錯誤,我可以看到:

  1. 你設置你latLng作爲根fb參考的孩子
  2. 您使用push()的,這似乎是一個結構一個命名子

這兩個解決方案:

fb.on("child_added", function(snapshot) { 
    var place = snapshot.val(); 
    if (place.hasOwnProperty('longitude') && place.hasOwnProperty('latitude')) { 
    snapshot.ref().child('latLng').set({lat: place.latitude, lng: place.longitude}); 
    }; 
}, function (errorObject) { 
    console.log("The read failed: " + errorObject.code); 
}); 
+0

謝謝你,弗蘭克。如果按latLng命名,則意味着它已經是im對象上的一個屬性,事實並非如此。我爲每個對象創建一個新的鍵和值,如果它已經有lat和long屬性的話。在這種情況下,你的解決方案仍然被推薦?再次感謝。此解決方案工作。謝謝。 – idkjs

相關問題