Send Geolocation Data to Firebase(how to assing it)


#1

Im trying to send user location data when user press sendmessage button.so each message in db will have location data.

This is model:

export interface Message{
    $key?: string,
    message: string,
    locationlat: number,
    locationlong: number
}

The problem is im assigning message with using ngModel in html file.But how do i assing locationlat and locationlong with data?

    import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import {AngularFireAuth} from 'angularfire2/auth';
import {AngularFireDatabase,FirebaseListObservable} from 'angularfire2/database';
import {Message} from '../../models/message';
import { Geolocation } from '@ionic-native/geolocation';



@Component({
  selector: 'page-newpost',
  templateUrl: 'newpost.html'
})
export class NewPostPage {
  message = {} as Message;

    messageRef$ : FirebaseListObservable<Item[]>;

  constructor(private fire:AngularFireAuth,private db :AngularFireDatabase,public navCtrl: NavController,private geolocation: Geolocation) {
    this.messageRef$ = this.db.list('messages');



}


sendPost(message:Message){
  this.geolocation.getCurrentPosition().then((resp) => {
      var lat =resp.coords.latitude;
    var long =resp.coords.longitude;
    console.log(lat);
    console.log(long);
  }).catch((error) => {
    console.log('Error getting location', error);
  });



  const promise =  this.messageRef$.push({
          message : message.message,
          //locationlat : , //need to fix them
          //locationlong :
      });
      promise
          .then(_ => {
              console.log('message added');
              this.message = {} as message;

          } )



}


}

#2

getCurrentPosition is asynchronous, so you’ll need to send the message within the then. Something like this:

sendPost(message:Message){
  return this.geolocation.getCurrentPosition().then((resp) => {
    var lat =resp.coords.latitude;
    var long =resp.coords.longitude;
    console.log(lat);
    console.log(long);

    return this.messageRef$.push({
      message : message.message,
      locationlat: lat,
      locationlong: long
    });
  })
  .then(_ => {
    console.log('message added');
    this.message = {} as message;
  })
  .catch((error) => {
    console.log('Error getting location', error);
  });
}

#3

wow thanks so much its working.


#4

hi, can i know where you put this code ?

export interface Message{
$key?: string,
message: string,
locationlat: number,
locationlong: number
}