【问题标题】:How to write geolocation data as an array into Google Firebase Realtime Database with Angular HttpClient?如何使用 Angular HttpClient 将地理位置数据作为数组写入 Google Firebase 实时数据库?
【发布时间】:2019-12-23 21:15:53
【问题描述】:

我正在尝试用Cordova Geolocation pluginAndroid构建一个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);
  }
}

【问题讨论】:

标签: angularjs typescript firebase cordova ionic-framework


【解决方案1】:

您应该使用 firebase 的 api,而不是使用 post。首先初始化 thr db:

  // Set the configuration for your app
  // TODO: Replace with your project's config object
  var config = {
    apiKey: "apiKey",
    authDomain: "projectId.firebaseapp.com",
    databaseURL: "https://databaseName.firebaseio.com",
    storageBucket: "bucket.appspot.com"
  };
  firebase.initializeApp(config);

  // Get a reference to the database service
  var database = firebase.database();

然后就可以往数据库中添加数据了:

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

https://firebase.google.com/docs/database/web/read-and-write

【讨论】:

  • 您好,感谢您的回答,但连接已设置并且工作正常。我想这与 watchLocation() 函数有关。
【解决方案2】:

最好使用GeoFire。这需要节点的特定结构,但它允许通过 GPS 定位进行查询。

另见Location Queries With Firebase GeoFire and Angular Google Maps (AGM)

【讨论】:

    猜你喜欢
    • 2020-04-20
    • 1970-01-01
    • 1970-01-01
    • 2021-07-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-01
    相关资源
    最近更新 更多