【发布时间】:2019-12-23 21:15:53
【问题描述】:
我正在尝试用Cordova Geolocation plugin 在Android 上构建一个Ionic geolocation tracking app。到目前为止,跟踪实现工作正常。现在我想将Angular HttpClient 的坐标写入Firebase Realtime DB。但不知何故,它不起作用。
与Firebase RDB 的连接工作正常,如果我只写一个坐标,例如resp.coords.latitude。但是,如果我尝试用lat and lng 编写完整的数组,它就不再起作用了。
坐标将显示在console.log 中,但不在我们的Firebase RDB 中。
我想这可能是watchLocation() function 的问题。
有人知道如何解决这个问题吗?
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);
}
}
【问题讨论】:
-
我在您的问题中没有看到任何写入 Firebase 的代码。我忽略了什么吗?如果您不熟悉与 Firebase 交互,我建议您从这里开始:firebase.google.com/docs/database/web/start
标签: angularjs typescript firebase cordova ionic-framework