Guide on storing geolocation information in an array on Google Firebase Realtime Database using Angular HttpClient

I have been working on developing an innovative

Android geolocation tracking app using Ionic
with the assistance of the Cordova Geolocation plugin. The tracking feature has been successfully implemented thus far. However, I am currently facing challenges when attempting to utilize Angular HttpClient to store the coordinates in the Firebase Realtime DB.

The connection to the Firebase RDB functions properly when writing a single coordinate such as resp.coords.latitude. Yet, when trying to write the complete array containing lat and lng, it ceases to work.

Although the coordinates are being displayed in the console.log, they do not appear in our Firebase RDB.

I suspect that there might be an issue within the watchLocation() function.

Any suggestions on how to resolve this?

tracking.page.ts

import { Component, OnInit } from '@angular/core';
import { Geolocation } from '@ionic-native/geolocation/ngx';
import * as moment from 'moment';
import { GeolocationService } from '../../app/geolocation.service';

@Component({
  selector: 'app-tracking',
  templateUrl: './tracking.page.html',
  styleUrls: ['./tracking.page.scss'],
})
export class TrackingPage implements OnInit {
  geoLatitude: number;
  geoLongitude: number;
  geoAccuracy: number;
  timestamp: any;

  watchLocationUpdates: any;
  isWatching: boolean;

  constructor(
    private geolocation: Geolocation,
    public geolocationService: GeolocationService,
  ) { }

  getMoment() {
    return moment().milliseconds(0);
  }

  ngOnInit() {
    document.addEventListener('deviceready', onDeviceReady, false);
    function onDeviceReady() {
        console.log('navigator.geolocation works well');
    }
  }

      // Start location update watch
      watchLocation() {
        const options = {
          maximumAge: 3600000,
          timeout: 3000,
          enableHighAccuracy: true,
       };
        this.isWatching = true;
        this.watchLocationUpdates = this.geolocation.watchPosition(options);
        this.watchLocationUpdates.subscribe((resp) => {
          this.geoLatitude = resp.coords.latitude;
          this.geoLongitude = resp.coords.longitude;
          this.geoAccuracy = resp.coords.accuracy;
          console.log('watchLocation function called', resp);
          this.geolocationService.insertUserGeolocation(resp)
            .subscribe(() => {
              localStorage.setItem('lastLocation', JSON.stringify(resp));
              console.log(`user location data inserted in FB`, resp);
            });
         });
    }

      // Stop location update watch
      stopLocationWatch() {
        this.isWatching = false;
        console.log('this.isWatching = ', this.isWatching);
        this.watchLocationUpdates.unsubscribe();
      }
}

geolocation.service.ts

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { environment  } from '../environments/environment';

@Injectable({
  providedIn: 'root'
})
export class GeolocationService {
  databaseUrl = environment.firebase.databaseURL;

  constructor(private http: HttpClient) {
    console.log('Hello OrganizationService Provider');
    console.log('OrganizationService: ', this.databaseUrl);
  }

  insertUserGeolocation(data) {
    return this.http.post(`${this.databaseUrl}/geolocations.json`, data);
  }
}

Answer №1

Don't rely on using the post method, instead leverage Firebase's API. Start by initializing the database:

  // Configure your app
  // Remember to replace with your project's config details
  var config = {
    apiKey: "apiKey",
    authDomain: "projectId.firebaseapp.com",
    databaseURL: "https://databaseName.firebaseio.com",
    storageBucket: "bucket.appspot.com"
  };
  firebase.initializeApp(config);

  // Access the database service
  var database = firebase.database();

After that, you can insert data into the database:

function writeUserData(userId, name, email, imageUrl) {
  firebase.database().ref('users/' + userId).set({
    username: name,
    email: email,
    profile_picture : imageUrl
  });
}

Learn more about reading and writing data in Firebase here.

Answer №2

I recommend utilizing GeoFire for better results. This plugin requires a specific tree structure, enabling GPS fix queries.

For additional information, check out Exploring Location Queries Using Firebase GeoFire and Angular Google Maps (AGM).

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The system encountered an error when attempting to convert the data '19-10-2002' into a date format

I am trying to pass a date parameter in the format (dd-MM-yyyy) and then convert it into the format (yyyy-MM-dd) before sending it via API. Here is my code: convert(date:string){ date //is in the format(dd-MM-yyyy) date = formatDate(date , " ...

Exploring for JSON keys to find corresponding objects in an array and adding them to the table

I'm currently working on a project where I need to extract specific objects from a JSON based on an array and then display this data in a table. Here's how my situation looks: playerIDs: number[] = [ 1000, 1002, 1004 ] The JSON data that I am t ...

Emphasizing terms with angular edges

I am struggling to implement a feature where users can click on a word within a specific div and have it highlighted. Despite my efforts, I realize that what I have created is far from functional. I have watched numerous tutorials and read various articles ...

The color syntax in the text editor of Visual Studio 2022 is being lost when casting an interface

After attempting to cast an interface, the entire code turns white. let object : someInterface = <someInterface> someUnknownHapiRequestPayload View a screenshot of the text editor here I have already tried common troubleshooting steps such as updat ...

Using the keyof operator to determine the data type of a property within a TypeScript class

According to TypeScript's documentation on the keyof operator, you can access a property of an object instance using this function below. function getProperty<T, K extends keyof T>(o: T, name: K) { return o[name]; } If you want to obtain th ...

Issue with constructor including an interface

I'm facing an issue with a typescript class that has an interface implemented in the constructor parameter: interface responseObject { a: string; b: boolean; c?: boolean; } class x { a: string; b: boolean; ...

Exploring the world of AngularJS and delving into the

Lately, I've come across articles discussing Google's ability to now crawl websites and render CSS and Javascript. For example, Google themselves have talked about it in this article: My setup involves a single page application built with Angula ...

Transporting a Typescript file to the customer using JavaScript

As a newcomer to typescript and in the process of creating a small application in visual studio 2013, I have noticed that when viewing the project in Chrome's developer tools, typescript files (*.ts) are being downloaded to the client. This could pote ...

Issues arise when trying to type ChangeEvent in React using Typescript

After spending some time learning React with TypeScript, I encountered a problem. The prop onChangeHandler in my code takes a function to modify properties in formik values. <Formik<FormModel> initialValues={{ favorite: ...

Chrome fails the karma tests while phantomjs passes them

I've been struggling with this issue for some time now and can't seem to find a solution. I'm working on an Ionic 2 project that utilizes Angular 2's testing environment. When I run 'ng test' using Karma's Chrome launcher ...

Interactive map with AngularJS featuring dynamic markers and real-time updating of marker position

In my Angular application, I have integrated a Google Map with a marker. I am looking to make the marker move along with the map as it is being moved. Currently, the marker stays in its default position when the map is moved. How can I achieve the effect ...

Refreshing a page when using html5Mode with a base tag may not function properly

AngularJS - html5Mode Issue: Cannot GET /login After coming across a similar post regarding this issue, I implemented the base tag to ensure relative URLs work properly. Additionally, I have included $locationProvider.html5Mode(true); in my application. W ...

Retrieve data from a Firestore document in an Ionic application

I have a service that retrieves a specific document from Firestore using the getBidremains method. The method in the TypeScript class is called in ngOnInit like this: this.userInfo = this.firestoreService.getBidremains(userId).valueChanges().subscribe(da ...

What is the most efficient way to retrieve all documents from all parent collections in Firebase Firestore asynchronously?

My current challenge involves retrieving all the documents from every collection within a Firestore database structured as shown below: -users(collection) -user1 (document) -snippets(collection) -snippetdId1 (document) - ...

The Angular Tooltip feature is unable to interpret the characters "' '" or "' '"

Let me explain the scenario: I am receiving a list of objects from my back-end service, which I then break apart using ngFor and display accordingly. Each item in the list has an associated toolTip that provides additional information. The info for each i ...

The issue I'm facing is that the style loader is failing to load the CSS within the <head

I am currently facing an issue with importing my CSS into my webpack bundle for our Angular 1 application. Initially, everything was working fine as we bundled our application using Webpack. The HTML included the bundle and vendor scripts, additional Java ...

Unable to invoke the AppComponent function within ngOnInit due to error message: "Object does not have the specified property or method"

I'm a novice in Angular and I am attempting to invoke my function setCenter2() from the AppComponent class within the ngOnInit function of the same class. Is this achievable? Whenever I try to call my function by clicking on the map (using OpenStreetM ...

Error: Unhandled promise rejection - The function get is not part of this.categoryMap

I am facing an issue with calling functions of the Map (get, set, keys, etc) within my function. The map I am working with is returned from a firebase query. Here's a snippet of my code: categoryMap = new Map<Number, String>(); //called onInit ...

Accelerated repository uses TypeScript to compile a node application with dependencies managed within a shared workspace

Struggling to set up an express api within a pnpm turborepo workspace. The api relies on @my/shared as a dependency, which is a local workspace package. I have been facing challenges in getting the build process right. It seems like I need to build the s ...

Exploring the world of Typescript and Angular Filter functionalities

I am looking to utilize one of my Angular Filters in my controller as a function. I came across a solution on this page: How to use a filter in a controler The last answer provided exactly what I needed, so I implemented it in my JS code: var MyFunc ...