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);
}
}