get lat and long from all firebase documents - firebase

I am trying to get location from all documents of my collection, but in this way I am getting just one document lat and long.
I need to get all lat and long data from all documents and show it in my map
what I am doing wrong??
can anyone help me with it??
POINTS STATE:
const [points, setPoints] = useState([]);
useEffect(() => {
async function getProviderLocation() {
try {
const db = firestore();
await db
.collection('Providers')
.get()
.then(snapshot => {
if (snapshot.empty) {
console.log('nao tem');
return;
}
console.log('docss', snapshot.docs);
snapshot.forEach(async doc => {
// console.log('ID', doc.id);
setPoints([
...points,
{
id: doc.id,
latitude: doc.data().address.latitude,
longitude: doc.data().address.longitude,
},
]);
console.log('points', points);
});
})
.catch(err => {
console.log('Error getting documents', err);
});
} catch (error) {
console.log(error);
}
}
if (coordinates) getProviderLocation();
}, []);
RENDERING:
{points.map(point => (
<Marker
onPress={() => navigateToCreateAppointment(point.id)}
style={styles.mapMarkerImage}
key={point.id}
coordinate={{
latitude: parseFloat(point.latitude),
longitude: parseFloat(point.longitude),
latitudeDelta: 0.015,
longitudeDelta: 0.0121,
}}
>
<Image source={wingImg} />
</Marker>
))}

Related

How to render lists using React Native and Firestore

I'm doing Expo React Native Application using Firestore Database. I'm following the below Tutorial.
Tutorial
function ViewServices () {
const navigation =useNavigation();
const [FullData, setFullData] = useState([]);
const [driverData, setDriverData] = useState([]);
// Retrieving Data
useEffect(() => {
firebase.firestore().collection('driver')
.get()
.then(snapshot => {
if (snapshot.empty) {
console.log('Empty');
return;
}
snapshot.forEach(doc => {
driverData.push(
{
id: doc.id,
});
});
{
driverData? driverData.map((point) => (
firebase.firestore().collection('driver')
.doc(point.id)
.collection('personal')
.get()
.then(snapshot => {
if (snapshot.empty) {
alert('Nothing To Show');
return;
}
snapshot.forEach(doc => {
FullData.push(
{
id : doc.id,
name: (doc.data().firstname),
school: (doc.data().lastname),
});
});
setFullData(FullData);
})
.catch(err => {
console.log('Error getting documents', err);
})
))
: null}
})
.catch(err => {
console.log('Error getting documents', err);
});
}, []);
return(
<FlatList
data={FullData}
renderItem={({ item }) => (
<View style={{ height: 50, flex: 1, alignItems: 'center',
justifyContent: 'center' }}>
<Text>User ID: {item.id}</Text>
<Text>User Name: {item.name}</Text>
</View>
)}
/>
)}
However the data are retrieved fine. But the lists are only shown when I manually press Refresh (Ctrl+S)
How can I retrieve the lists when the screen loads? Please let me know.
I found a solution.
The problem happened because the components are firstly rendered before the data fetching. That's why it required manual refresh.
I have added Activity Indicator component and it will be loaded until the data fetched. After the data successfully fetched, activity indicator will be replaced with flat list component.
function ViewServices () {
**const [loading, setLoading] = useState(true)**
const navigation =useNavigation();
const [FullData, setFullData] = useState([]);
const [driverData, setDriverData] = useState([]);
// Retrieving Data
useEffect(() => {
firebase.firestore().collection('driver')
.get()
.then(snapshot => {
if (snapshot.empty) {
console.log('Empty');
return;
}
snapshot.forEach(doc => {
driverData.push(
{
id: doc.id,
});
});
{
driverData? driverData.map((point) => (
firebase.firestore().collection('driver')
.doc(point.id)
.collection('personal')
.get()
.then(snapshot => {
if (snapshot.empty) {
alert('Nothing To Show');
return;
}
snapshot.forEach(doc => {
FullData.push(
{
id : doc.id,
name: (doc.data().firstname),
school: (doc.data().lastname),
});
});
setFullData(FullData);
**setLoading(false);**
})
.catch(err => {
console.log('Error getting documents', err);
})
))
: null}
})
.catch(err => {
console.log('Error getting documents', err);
});
}, []);
**if (loading) {
return (
<ActivityIndicator size="large" color="#00ff00" justifyContent= "center"/>
)
}**
else{
return(
<FlatList
data={FullData}
renderItem={({ item }) => (
<View style={{ height: 50, flex: 1, alignItems: 'center',
justifyContent: 'center' }}>
<Text>User ID: {item.id}</Text>
<Text>User Name: {item.name}</Text>
</View>
)}
/>
)
}
}

because my return is [{"singles": [[Object], [Object]]}]

I am using a useEffect to get information from a collection and a sub-collection, however, the data return from my sub-collection is being [{"singles": [[Object], [Object]]}]
useEffect(() => {
fireStore
.collection('users')
// .where('category','==','band')
// .where('status','==','approved')
.where('email','==','marcelomenoli12#gmail.com')
.get()
.then( async (musics) => {
const allSingles = musics.docs.map(async (single) => {
const items = await single.ref.collection('musics').get();
return {
// cover: single.data().cover,
// name: single.data().bandArtistName,
singles: items.docs.map((item) => ({
id: item.id,
...item.data(),
}))
}
});
const filteredSingles = await Promise.all(allSingles);
setDATA(filteredSingles);
});
}, []);
console.log(DATA);
You should use more than one then clauses, so every async operation return values. Otherwise inner await responses are not come on time.
I tried to update your code. I hope that helps.
useEffect(() => {
fireStore
.collection('users')
.where('email','==','marcelomenoli12#gmail.com')
.get()
.then( async (musics) => {
const allSingles = musics.docs.map(async (single) => {
return await single.ref.collection('musics').get();
})
.then((items)=>{
// cover: single.data().cover,
// name: single.data().bandArtistName,
singles: items.docs.map((item) => ({
id: item.id,
...item.data(),
}))
})
}, []);
console.log(DATA);

Ionic 3 File-Transport multipart/form-data

i am actually working on a mobile app in ionic v3 with angular5
The goal is to be able to take a picture or choose from existing ones and then upload it to the server. The first part is done, but i am struggling with the upload.
The api needs multipart/form-data which must consist of two requests. First with text part and second is the image.
Is there any solution for this?
This is what I have done for similar requirement
takePhoto() {
this.camera.getPicture({
quality: 100,
destinationType: this.camera.DestinationType.FILE_URI,
sourceType: this.camera.PictureSourceType.CAMERA,
encodingType: this.camera.EncodingType.PNG,
saveToPhotoAlbum: true
}).then(imageData => {
this.myPhoto = imageData;
this.uploadPhoto(imageData);
}, error => {
this.functions.showAlert("Error", JSON.stringify(error));
});
}
selectPhoto(): void {
this.camera.getPicture({
sourceType: this.camera.PictureSourceType.PHOTOLIBRARY,
destinationType: this.camera.DestinationType.FILE_URI,
quality: 100,
encodingType: this.camera.EncodingType.PNG,
}).then(imageData => {
this.myPhoto = imageData;
this.uploadPhoto(imageData);
}, error => {
this.functions.showAlert("Error", JSON.stringify(error));
});
}
private uploadPhoto(imageFileUri: any): void {
this.file.resolveLocalFilesystemUrl(imageFileUri)
.then(entry => (<FileEntry>entry).file(file => this.readFile(file)))
.catch(err => console.log(err));
}
private readFile(file: any) {
const reader = new FileReader();
reader.onloadend = () => {
const formData = new FormData();
const imgBlob = new Blob([reader.result], { type: file.type });
formData.append('evaluationID', this.currentEvaluation.evaluationId);
formData.append('standardID', this.currentEvaluation.id);
formData.append('score', this.currentEvaluation.score);
formData.append('comment', this.currentEvaluation.comment);
formData.append('file', imgBlob, file.name);
this.saveStandard(formData);
};
reader.readAsArrayBuffer(file);
}
And here is code for provider
saveStandard(receivedStandardInfo:any){
return new Promise((resolve, reject) => {
this.http.post(apiSaveStandard,receivedStandardInfo)
.subscribe(res => {
resolve(res);
}, (err) => {
console.log(err);
reject(err);
});
}).catch(error => { console.log('caught', error.message); });
}

How to sync data to Realm Object Server from NodeJS?

I could register user(not admin), login, and store data in local.
But my program doesn't sync data to ROS2.
As far as I see document, maybe using Realm.Sync.addListener with admin.
I think admin user can access all object data. is wrong?
const addListener = (user) => new Promise((resolve, reject) => {
Realm.Sync.addListener('realm://usme-ros.usme.local:9080', user, '.*', 'change', (back) => {
console.log(back);
});
});
const registerUser = () => new Promise((resolve, reject) => {
Realm.Sync.User.register(URL, username, password, (err, res) => {
if (err) {
return reject(err);
}
console.log('finish register');
resolve();
})
});
const login = () => new Promise((resolve, reject) => {
Realm.Sync.User.login(URL, username, password, (err, user) => {
if (err) {
return reject(err);
}
resolve(user);
})
});
const registerVisit = (token) => new Promise((resolve, reject) => {
const visitSchema = {
name: 'Visit',
properties: {
id: 'int',
oneday_id: 'string',
arrival_date: 'string',
departure_date: 'string',
latitude: 'double',
longitude: 'double',
is_hidden: 'bool',
}
};
Realm.openAsync({ schema: [visitSchema] }, (err, realm) => {
if (err) {
return reject(err);
}
realm.write(() => {
realm.create('Visit', {
id: 1,
oneday_id: "ABCD-EFGH-IJKL-MNOP-QRST",
arrival_date: "2017-11-05 11:11:11",
departure_date: "2017-11-05 22:22:22",
latitude: 23.1234567,
longitude: 12.34567,
is_hidden: false,
});
});
resolve();
});
});
login()
.then((user) => addListener(user)
.then(() => registerVisit())
.catch(err => console.log(err)));

React Native / Firebase - upload image with additional info

I used this block of code to select an image when button is pressed to upload to firebase.
<TouchableHighlight onPress={ () => this._pickImage() }
style={styles.button}>
<Text
style={styles.buttonText}>
Select a Photo
</Text>
</TouchableHighlight>
_pickImage() {
this.setState({ uploadURL: '' })
ImagePicker.launchImageLibrary({}, response => {
uploadImage(response.uri)
.then(url => this.setState({ uploadURL: url }))
.catch(error => console.log(error))
});
}// end _pickImage
const uploadImage = (uri, mime = 'application/octet-stream') => {
return new Promise((resolve, reject) => {
const uploadUri = Platform.OS === 'ios' ? uri.replace('file://', '') : uri
const sessionId = new Date().getTime()
let uploadBlob = null
const imageRef = storage.ref('images').child(`${sessionId}`)
fs.readFile(uploadUri, 'base64')
.then((data) => {
return Blob.build(data, { type: `${mime};BASE64` })
})
.then((blob) => {
uploadBlob = blob
return imageRef.put(blob, { contentType: mime })
})
.then(() => {
uploadBlob.close()
return imageRef.getDownloadURL()
})
.then((url) => {
resolve(url)
})
.catch((error) => {
reject(error)
})
})
}
This works fine. How can I change this to let the user select photo and then hit another button store additional info for the image like Description entered by the user into the same data structure in firebase?

Resources