Как создать новое дерево JSON с машинописью? - PullRequest
0 голосов
/ 01 марта 2020

Я пытаюсь создать мобильное приложение для отслеживания геолокации Ioni c (Angular). Отслеживание местоположения уже работает довольно хорошо. Но теперь я хочу хранить геолокации в маршрутах. На данный момент каждый набор данных (точность, длинна, широта ...) будет сохраняться отдельно в базе данных Firebase Realtime.

Кто-нибудь знает, как решить эту проблему?

Цель состоит в том, чтобы иметь такую ​​структуру:

-geolocations
    - routeId
        - trackingId
            - accuracy
            - long
            - lat
            - timeStamp
            - uId

Старая структура выглядит следующим образом: enter image description here

tracking.page.ts

import { Component, OnInit, ViewChild, ElementRef } from '@angular/core';
import { Geolocation } from '@ionic-native/geolocation/ngx';
import { GeolocationService } from '../../app/geolocation.service';
import { UserService } from '../../app/user.service';
import { Insomnia } from '@ionic-native/insomnia/ngx';
import { LoadingController } from '@ionic/angular';
import { AlertController } from '@ionic/angular';
import { AppComponent } from '../app.component';
import { Storage } from '@ionic/storage';

declare var google;

@Component({
  selector: 'app-tracking',
  templateUrl: './tracking.page.html',
  styleUrls: ['./tracking.page.scss'],
})
export class TrackingPage implements OnInit {
  @ViewChild('map', { static: true }) mapElement: ElementRef;
  map: any;
  markers = [];
  geoLocations: any;

  watchLocationUpdates: any;
  isWatching: boolean;
  interval: any;

  geoLatitude: number;
  geoLongitude: number;
  geoAccuracy: number;
  timeStamp: any;
  uId: string;
  trackingId: string;

  constructor(
    private geolocation: Geolocation,
    public geolocationService: GeolocationService,
    public userService: UserService,
    private insomnia: Insomnia,
    public loadingCtrl: LoadingController,
    public alertController: AlertController,
    public appComponent: AppComponent,
    private storage: Storage
    ) {
  }

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

    this.appComponent.isLoggedIn = true;

    this.loadMap();
      console.log('this.loadMap() called');
  }

  loadMap() {
    const latLng = new google.maps.LatLng(48.141558, 11.568210);
    const mapOptions = {
      center: latLng,
      zoom: 10,
      mapTypeId: google.maps.MapTypeId.ROADMAP,
      mapTypeControl: false,
      streetViewControl: false,
      fullscreenControl: false,
      zoomControl: false
    };
    this.map = new google.maps.Map(this.mapElement.nativeElement, mapOptions);
  }

  // Start location watch
  watchLocation() {
    this.loadingCtrl.create({
      message: 'Standort Tracking wird initialisiert...',
      duration: 5000,
    }).then((res) => {
      res.present();
    });
    const options = {
      maximumAge: 3000,
      timeout: 5000,
      enableHighAccuracy: true,
    };
    this.isWatching = true;
    this.insomnia.keepAwake()
    .then(
      () => console.log('this.insomnia.keepAwake(): success')
    );
    this.trackingId =  Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15);
    this.interval = setInterval(() => {
      this.uId = this.userService.uId;
      if (this.appComponent.userName !== '') { // Makes sure that username is loaded from db
      this.watchLocationUpdates = this.geolocation.getCurrentPosition(options);
      this.watchLocationUpdates.then((resp) => {

        this.geoLocations = resp.coords;
        this.geoLatitude = resp.coords.latitude;
        this.geoLongitude = resp.coords.longitude;
        this.geoAccuracy = Math.trunc(resp.coords.accuracy);
        this.timeStamp = Date.now();

        this.geolocationService.insertUserGeolocation({
          trackingId: this.trackingId,
          latitude: this.geoLatitude,
          longitude: this.geoLongitude,
          accuracy: this.geoAccuracy,
          timeStamp: this.timeStamp,
          uId: this.uId
          }).subscribe((response) => {
            localStorage.setItem('lastLocation', JSON.stringify({
              trackingId: this.trackingId,
              latitude: this.geoLatitude,
              longitude: this.geoLongitude,
              accuracy: this.geoAccuracy,
              timeStamp: this.timeStamp,
              uId: this.uId
              }));
            console.log(`user location data inserted in FB`, {
              trackingId: this.trackingId,
              latitude: this.geoLatitude,
              longitude: this.geoLongitude,
              accuracy: this.geoAccuracy,
              timeStamp: this.timeStamp,
              uId: this.uId
              });
          });

        const position = new google.maps.LatLng(resp.coords.latitude, resp.coords.longitude);
        this.map.setCenter(position);
        this.map.setZoom(16);

        this.markers.map(marker => marker.setMap(null));
        this.markers = [];
        const latLng = new google.maps.LatLng(resp.coords.latitude, resp.coords.longitude);
        const marker = new google.maps.Marker({
          map: this.map,
          icon: {
            path: google.maps.SymbolPath.CIRCLE,
            scale: 13,
            fillColor: '#1CA0EC',
            fillOpacity: 1,
            strokeColor: 'white',
            strokeWeight: 2
          },
            position: latLng
        });
        this.markers.push(marker);
      });
      } else {
      this.stopLocationWatch();
      }
    }, 3000);
  }

  // Stop location watch
  stopLocationWatch() {
    this.isWatching = false;
    console.log('this.isWatching = ', this.isWatching);
    clearInterval(this.interval);
    console.log('this.interval', this.interval);
    // this.watchLocationUpdatesSub.unsubscribe();
    this.loadMap();
    this.locationStopAlert();
    this.insomnia.allowSleepAgain()
      .then(
       () => console.log('this.insomnia.allowSleepAgain(): success'),
    );
  }

  async locationStopAlert() {
    const alert = await this.alertController.create({
      header: 'Das Standort Tracking wurde beendet',
      // message: 'This is an alert message.',
      buttons: ['OK']
    });
    await alert.present();
  }
}

1 Ответ

0 голосов
/ 02 марта 2020

Если я правильно понимаю, этот код, который я сделал для вас, должен помочь вам преобразовать старый формат в новый.

const geolocations = {
  routeId1: [
    { trackingId: 1, timeStamp: 1, accuracy: 1, longitude: 1, latitude: 1, uId: 1 },
    { trackingId: 1, timeStamp: 2, accuracy: 2, longitude: 2, latitude: 2, uId: 2 },
    { trackingId: 2, timeStamp: 1, accuracy: 3, longitude: 3, latitude: 3, uId: 3 },
    { trackingId: 2, timeStamp: 2, accuracy: 4, longitude: 4, latitude: 4, uId: 4 }
  ],
  routeId2: [
    { trackingId: 3, timeStamp: 1, accuracy: 5, longitude: 5, latitude: 5, uId: 5 },
    { trackingId: 4, timeStamp: 1, accuracy: 6, longitude: 6, latitude: 6, uId: 6 },
    { trackingId: 4, timeStamp: 2, accuracy: 7, longitude: 7, latitude: 7, uId: 7 },
    { trackingId: 4, timeStamp: 3, accuracy: 8, longitude: 8, latitude: 8, uId: 8 }
  ]
};
const newGeolocations = {};
const routesIds = Object.keys(geolocations);
for (const routeId of routesIds) {
  const route= geolocations[routeId];
  if (!newGeolocations.hasOwnProperty(route)) {
    newGeolocations[routeId] = {}
  }
  for (const loc of route) {
    if (!newGeolocations[routeId].hasOwnProperty(loc.trackingId)) {
      newGeolocations[routeId][loc.trackingId] = []
    }
    newGeolocations[routeId][loc.trackingId].push({
      accuracy: loc.accuracy,
      longitude: loc.longitude,
      latitude: loc.latitude,
      timeStamp: loc.timeStamp,
      uId: loc.uId
    });
  }
}
console.log(JSON.stringify(newGeolocations));

Это результат, который я получаю в консоли,

{
"routeId1":
    {"1":[
        {"accuracy":1,"longitude":1,"latitude":1,"timeStamp":1,"uId":1},
        {"accuracy":2,"longitude":2,"latitude":2,"timeStamp":2,"uId":2}
    ],
    "2":[
        {"accuracy":3,"longitude":3,"latitude":3,"timeStamp":1,"uId":3},
        {"accuracy":4,"longitude":4,"latitude":4,"timeStamp":2,"uId":4}
    ]},
"routeId2":{
    "3":[
        {"accuracy":5,"longitude":5,"latitude":5,"timeStamp":1,"uId":5}
    ],
    "4":[
        {"accuracy":6,"longitude":6,"latitude":6,"timeStamp":1,"uId":6},
        {"accuracy":7,"longitude":7,"latitude":7,"timeStamp":2,"uId":7},
        {"accuracy":8,"longitude":8,"latitude":8,"timeStamp":3,"uId":8}
    ]}
}

Дайте мне знать, поможет ли это вам.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...