I'm having an issue with saving data from Firebase Realtime Database to an array inside of a Vue component.
The main error I'm getting is: "Cannot read property 'savedLocations' of null".
The array is supposed to contain information about a post; including a title, a description, an image, and the location of the user. Every location is being saved to the database as a raw address and as geolocation (lat, lng) with the goal being displaying markers on a vue2-google-maps map.
The data from the form, containing all the information about the post, is being submitted in another view, so my primary issue is retrieving the data from firebase and displaying markers on the map.
The current code in which I'm getting the error is:
export default {
data() {
return {
// check for sign in:
signedIn: false,
// map information
map: null,
myCoordinates: {
lat: 0,
lng: 0
},
zoom: 12,
// locations:
savedLocations: []
}
},
async beforeMount() {
// reference to list of posts
var ref = db.ref("PhotoGallery");
ref.on("value", function(snapshot) {
snapshot.forEach((childSnapshot) => {
this.savedLocations.push(childSnapshot.val());
})
}, function (errorObject) {
console.log("The read failed: " + errorObject.code);
});
}
If I console.log all the childSnapshots, I do get all the items from the database output as objects in the console, each individually, but I do not know how to append them to an array so I could iterate through them and make markers based on their geolocation.
My goal is to be able to iterate through the array and make markers using the following code:
<google-map
:center="myCoordinates"
:zoom="zoom"
style="width:100vw; height: 100vh; max-width: 100%; margin: 0 auto;"
ref="mapRef"
@dragend="handleDrag"
>
<markermap
:key="index"
v-for="(m, index) in savedLocations"
:position="{lat: m.position.lat, lng: m.position.lng}"
:clickable="true"
:draggable="false"
/>
</google-map>
The format in which I'm saving the information to the database is the following:
const post = {
photo: this.img1,
title: this.title,
description: this.description,
position: {
lat: this.currentPlace.geometry.location.lat(),
lng: this.currentPlace.geometry.location.lng()
},
address: this.$refs.gmapAutocomplete.$refs.input.value
}
markerRef.push(post) // reference to database
Also, if there's an easier way to do this, that would be welcome as well. My goal is just to be able to make markers on the map based on the information in the database and when they're clicked, to expand them with the title and image.
Thank you for the help. Cheers!