简体   繁体   中英

p5 Javascript Updating draw elements from Firestore Database

I am very much a beginner programmer, but have managed to write a python script on a raspberry PI that successfully updates a Firestore database and pulls data using JavaScript . I am then intending to use this data to draw items using mappa and p5 on a canvas/map.

I can console out the Firestore object and see the data but for the life of me I cannot seem to use this data in the draw() function of p5. or as a global variable? Here is a very simplified version of the code to what I'm trying to do.

db = firebase.firestore();
docRef = db.collection("Aircraft_data").doc("Firebird");
docRef.get().then(function(doc) {
  console.log("Document data:", doc.data());
  b = doc.data()
  return b;
});

function draw(){

  text(b["Altitude"], 200, 200);

}

The most confusing thing is that I can console and see the data in chrome? console img

You are making async call, that's why you see the result in callback but not in following code section(s) (which most probably run earlier than callback).

P5 have structure functions , draw() is one of them and is (by default) looping. Make your variable global and wait while it's been initialized (or some other ):

let myData; // make it global

function preload() {
    db = firebase.firestore();
    docRef = db.collection("Aircraft_data").doc("Firebird");
    docRef.get().then(function(doc) {
      console.log("Document data:", doc.data());
      myData = doc.data();
    });
}

function draw(){
    if(!myData){ //check whether data is loaded. Change condition to proper one.
        // if data is not yet arrived just return as draw() is looping
        return;
    }
    // now the data is arrived, myData is initialized, we can continue
    text(myData["Altitude"], 200, 200);
    //it is possible to stop looping now:
    noLoop();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM