All files / src/app/touchpad/itinerary itinerary.service.ts

71.43% Statements 15/21
100% Branches 0/0
80% Functions 4/5
70% Lines 14/20

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84    1x 1x                           1x   6x                     1x 4x                       1x   1x     1x 1x           1x 1x                   1x                               1x  
import { Injectable } from '@angular/core';
import { saveAs } from 'file-saver';
const geojson = require('geojson');
const tokml = require('tokml');
 
/**
 * The interface for points in a KML file.
 */
interface KMLPoint {
  name: string;
  lat: number;
  lng: number;
}
 
@Injectable({
  providedIn: 'root'
})
export class ItineraryService {
 
  private itineraryPoints: KMLPoint[] = [];
 
  constructor() { }
 
  /**
   * Add a point to the service's current itinerary.
   *
   * @param pointName The name of the point to add.
   * @param latitude The latitude of the point to add.
   * @param longitude The longitude of the point to add.
   */
  addPoint(pointName: string, latitude: number, longitude: number) {
    this.itineraryPoints.push({
      name: pointName,
      lat: latitude,
      lng: longitude
    });
  }
 
  /**
   * Delete the last point in the service's current itinerary.
   *
   * @returns A boolean indicating if the last point could be deleted.
   */
  deleteLastPoint(): boolean {
    if (this.itineraryPoints.length === 0) {
      return false;
    }
 
    this.itineraryPoints.pop();
    return true;
  }
 
  /**
   * Clear the service's current itinerary.
   */
  clearItinerary() {
    this.itineraryPoints = [];
  }
 
  /**
   * Save the service's current itinerary in a KML file.
   *
   * @param filename The name of the file in which the itinerary must be saved.
   *
   * @returns A boolean indicating whether the itinerary could be saved.
   */
  saveItinerary(filename: string): boolean {
    if (this.itineraryPoints.length === 0) {
      return false;
    }
 
    const geojsonObject = geojson.parse(this.itineraryPoints, {Point: ['lng', 'lat']});
    const kmlNameDescription = tokml(geojsonObject, {
      documentName: 'Itinerary'
    });
 
    const file = new Blob([kmlNameDescription], {
      type: 'text/kml;charset=utf-9'
    });
    saveAs(file, filename + '.kml');
    return true;
  }
}