import {
  Component,
  ViewEncapsulation,
  OnInit,
  OnDestroy,
  ViewChild,
  ElementRef,
  NgZone,
} from "@angular/core";
import { FormControl } from "@angular/forms";
import { MdDialog, MdSnackBar } from "@angular/material";
import { Router, ActivatedRoute, Params } from "@angular/router";
import { FlashMessagesService } from "angular2-flash-messages";
import { BsDatepickerConfig } from "ngx-bootstrap";
import { Subject, Observable } from "rxjs";
import { AddpoiBylocationComponent } from "../../addpoi-bylocation/addpoi-bylocation.component";
import { ContactService } from "../../contact.service";
import { DatainjectionService } from "../../datainjection.service";
import { SidebarComponent } from "../../sidebar/sidebar.component";
import { SidemenuFuelComponent } from "../../sidemenu-fuel/sidemenu-fuel.component";
import { AddDeviceComponent } from "../add-device/add-device.component";
import { CmdUIComponent } from "../cmd-ui/cmd-ui.component";
import { CommandWindowComponent } from "../command-window/command-window.component";
import { CreateTripComponent } from "../create-trip/create-trip.component";
import { ImmobilizeComponent } from "../immobilize/immobilize.component";
import { ShareLocComponent } from "../share-loc/share-loc.component";
import { ShoRoutePlanComponent } from "../sho-route-plan/sho-route-plan.component";

import * as io from "socket.io-client";
import * as moment from "moment-timezone";
import { OpenMapComponent } from "../../open-map/open-map.component";
import { Data } from "../../data";

declare var jsPDF: any, _: any;
declare var html2canvas: any;

declare var swal: any;

/* import { Ng4LoadingSpinnerService } from 'ng4-loading-spinner';
 */
declare var google: any;
declare var maplibregl: any;
declare var MaplibreInspect: any;
// declare var MarkerClusterer: any;
declare var InfoBox: any;
declare var RadialGauge: any;
/* declare var Gauge: any;
 */
@Component({
  selector: "app-new-location",
  templateUrl: "./location.component.html",
  providers: [SidebarComponent],
  styleUrls: ["./location.component.scss"],
  encapsulation: ViewEncapsulation.None,
})
export class LocationNewComponent implements OnInit, OnDestroy {
  @ViewChild(OpenMapComponent) _openMapComponet: OpenMapComponent;
  @ViewChild(SidemenuFuelComponent) child1: SidemenuFuelComponent;
  @ViewChild("main") main: ElementRef;
  historyTrackData = {};
  modelChanged: Subject<string> = new Subject<string>();
  area = 0;
  toppings = new FormControl();
  socketIOData = {};
  toppingList: string[] = [
    "Extra cheese",
    "Mushroom",
    "Onion",
    "Pepperoni",
    "Sausage",
    "Tomato",
  ];
  imei;
  // private fuelComponent: SidemenuFuelComponent;
  showLabels: boolean = true;
  showAddress: boolean = false;
  showSocketData: boolean = false;
  satelliteDisabled: boolean = false;
  immobilizeChk: boolean = false;
  testData: any;
  reloadCOmponent: boolean;
  mapWidth: string;
  showButton: boolean = true;
  test_stop: any = [];
  Durations: string;
  park_icon = [];
  speeed_1 = 10;
  test_Data: any;
  timerGif = "../../assets/images/timerGif.gif";
  addresslocation: any;
  departureTime: string;
  arrivalTime: string;
  longitude: any;
  minIdleTime: number = 10;
  locations: any;
  latitude: any;
  stoppage_container: any = [];
  // stop_locations: any =[];
  departure: Date;
  arrival: Date;
  dev_id: any;
  //date: any
  MapLoad: boolean = true;
  loc: any;
  lcShr: Boolean = false;
  before: any;
  SpeedMeter: Boolean;
  zoomLevel: number;
  data_descip: any;
  superAdmin: Boolean = false;
  liveAdd: any = "";
  mapNew: any;
  trafficLayer: any;
  routeDetails: (uId: any, choice: any) => void;
  routeDetails1: (uId: any, choice: any) => void;
  latitudeInDMS: any;
  longitudeInDMS: any;
  toggleGeofence: (choice: any) => void;
  toggleGeofence1: (choice: any) => void;
  enabletrail: boolean = false;
  parkingButtonShow;
  selectedDevice;
  showHistory: boolean = false;
  togglePOI: (choice: any) => void;
  togglePOI1: (choice: any) => void;
  colorTheme = "theme-dark-blue";
  last_speed: string;
  DealerID: any;
  supAdm: any;
  deviceObj: any = [];
  dealerid: any;
  supadmin: any;
  deviceSelect: any = [];
  deviceName: any;
  stoppageCount: any;
  speedArr: any;
  maxSpeedd: any;
  dev_by_dashboard: string;
  latToPass: any;
  longToPass: any;
  directionsService: any;
  directionsDisplay: any;
  EndTripStartLat: any;
  EndTripStartLong: any;
  ETA: any;
  bsConfig: Partial<BsDatepickerConfig>;
  tripId: any;
  historyDate: any;

  goToPoint: () => void;
  moveMarker: () => void;
  marker4: any;
  start: any;
  historyMap: any;
  navId: String;
  deviceList: any = [];
  to: string;
  tab_1: boolean = false;
  tab_2: boolean = false;
  tab_3: boolean = false;
  from: string;
  total_vech: any;
  idle_vech: any;
  off_vech: any;
  maintanance: any;
  expiredDevices: any;
  OutOfReach: any;
  no_data: any;
  Running: any;
  idle_duration: any;
  off_duration: any;
  maintenance_ids: any;
  idle_ids: any;
  expired_ids: any;
  off_ids: any;
  runnigg: any;
  outofreach_ids: any;
  alldevvice: any;
  no_gps_name: any;
  id_running: any;
  id_stop: any;
  id_out: any;
  id_idel: any;
  unloading: any;
  loading: any;
  id_main: any;
  currentTime = new Date();
  not_on_root: any;
  cordin: any;
  temptrackingDev: any;
  buindhistoryDevice: any;
  currStatus: any;
  socketData: any;
  tempMapHistory: any = [];
  showTable: boolean = false;
  historyDataCondition: boolean = false;
  liveLocationMarkerObj: any;
  darkModeSwitch: boolean = false;
  tttttt: any = [];
  tabIndexValue: any = "0";
  tempDevInfo: any;
  cummulative_Distance: number = 0;
  token_identifier: string;
  contentAdd: string;
  historyAdress: any = "";
  gpsDataArr: any;
  ext_voltage: any;
  seekBarValue: any = 200;
  sliderValue: number = 0;
  indexValue: any;
  status_cmdq: any;
  intervalTimeOut: any;
  immobilizeCount: number;
  ImmErrMsg: string;
  showErr: boolean = false;
  unlocked: boolean = false;
  errIcon: boolean = false;
  locked: boolean = false;
  shoError: any;
  private socket_Notify;
  dealer_Permission: any;
  adbtn: string;
  markerArray: any;
  satelite = 5;
  dataSelect2: any;
  newArr = [
    { value: "1" },
    { value: "2" },
    { value: "3" },
    { value: "4" },
    { value: "5" },
    { value: "6" },
    { value: "7" },
    { value: "8" },
    { value: "9" },
    { value: "10" },
    { value: "11" },
    { value: "12" },
    { value: "13" },
    { value: "14" },
    { value: "15" },
  ];
  distanceVariation: any;
  digitalInput: any;
  myaccount() {
    this.cond = false;
    this.router.navigateByUrl("accountSettings");
  }

  filterStates1(val) {
    if (val) {
      const filterValue: any = val;
      1;
      this.dataSelect2 = this.newArr.filter(function (d) {
        return (
          d.value.toLocaleLowerCase().indexOf(filterValue.toLocaleLowerCase()) >
          -1
        );
      });
      if (this.dataSelect2.length != 0) {
        this.satelite = val;
      }
      return this.dataSelect2;
    }
  }
  searchFilter(text: string, strID) {
    var searchobj = {
      str: text,
      identifier: strID,
    };
    var tempSearch = JSON.stringify(searchobj);

    this.modelChanged.next(tempSearch);
  }
  switchToMap() {
    let url = window.location.href;
    url = url.replace("/location", "/glocation");
    localStorage.removeItem("isMapType");
    window.location.replace(url);
  }
  addcus() {
    localStorage.removeItem("mapLoad_ID");
    this.router.navigateByUrl("add");
  }
  ign() {
    this.router.navigateByUrl("device-report/ign-report");
  }
  shareLocation(device) {
    if (this.new) {
      if (this.new == null || this.new == undefined) {
        this.tost1("shrlcnd");
      } else {
        let dialogRef = this.dialog.open(ShareLocComponent, {
          width: "528px",
          data: { did: device.Device_ID, dname: device.viewValue },
        });

        dialogRef.afterClosed().subscribe((result) => {
          if (result == "shareloc") {
            this.new = null;
            this.tost1("shareloc");
          }
        });
      }
    } else if (this.prev_map) {
      if (this.prev_map == null || this.prev_map == undefined) {
        this.tost1("shrlcnd");
      } else {
        /*       window.localStorage['mapLoad_Name'] = name */

        let dialogRef = this.dialog.open(ShareLocComponent, {
          width: "528px",
          data: { did: this.prev_map, dname: window.localStorage.mapLoad_Name },
        });

        dialogRef.afterClosed().subscribe((result) => {
          if (result == "shareloc") {
            this.tost1("shareloc");
          }
        });
      }
    } else {
      this.tost1("shrlcnd");
    }
  }

  // TOAST
  tost1(divid) {
    if (divid == "shareloc") {
      this.data_descip = "Location Sucessfully Shared";
      launch_toast();
    } else if (divid == "nullsrlc") {
      this.data_descip = "Please Enter ether Email ID or Phone Number";
      launch_toast();
    } else if (divid == "shrlcnd") {
      this.data_descip = "Please Select any Device";
      launch_toast();
    } else if (divid === "added") {
      this.data_descip = "Device added";
      launch_toast();
    }

    function launch_toast() {
      var x = document.getElementById("toast");

      x.className = "show";
      setTimeout(function () {
        x.className = x.className.replace("show", "");
      }, 1500);
    }
  }
  dataa: any;

  settings = {
    /*  bigBanner: true, */
    date1: new Date().setHours(0, 0, 0),
    date2: new Date(),
    timePicker: true,
    format: "dd-MMM-yyyy hh:mm a",
    closeOnSelect: true,

    /*   defaultOpen: true */
  };
  logout() {
    window.localStorage.clear();
    this.router.navigateByUrl("login");
  }
  devi() {
    localStorage.removeItem("mapLoad_ID");
    this.router.navigateByUrl("dashboard");
  }

  ignition_report() {
    this.cond = false;
    this.router.navigateByUrl("device-report/ignition_report");
  }

  geofancingReport() {
    this.cond = false;
    this.router.navigateByUrl("device-report/geofancing");
  }
  Ddetail() {
    this.router.navigateByUrl("driverdetail");
  }
  DModel() {
    this.router.navigateByUrl("deviceModel");
  }
  VType() {
    this.router.navigateByUrl("VehicleType");
  }

  distance_report() {
    this.cond = false;
    this.router.navigateByUrl("device-report/distance_report");
  }

  summaryReport() {
    this.cond = false;
    this.router.navigateByUrl("device-report/summary-report");
  }
  overspeed() {
    this.cond = false;
    this.router.navigateByUrl("device-report/overspeed");
  }
  stoppage_report() {
    this.cond = false;
    this.router.navigateByUrl("device-report/stoppage_report");
  }

  routeViolation() {
    this.cond = false;
    this.router.navigateByUrl("device-report/routeViolation");
  }

  alert_report() {
    this.cond = false;
    this.router.navigateByUrl("device-report/alert_report");
  }

  group() {
    this.cond = false;
    this.router.navigateByUrl("group_view");
  }

  soon() {
    localStorage.removeItem("mapLoad_ID");
    this.router.navigateByUrl("const");
  }
  point: any = 0;
  a() {
    if (this.point == 0) {
      this.cond = true;
      this.point++;
    } else if (this.point % 2 == 0) {
      this.cond = true;
      this.point++;
    } else {
      this.cond = false;
      this.point++;
    }
  }
  report() {
    this.cond = false;
    localStorage.removeItem("mapLoad_ID");
    this.router.navigateByUrl("device-report");
  }

  vehicleRoute() {
    this.router.navigateByUrl("vehicleRoute");
  }

  dealerInfo() {
    this.cond = false;
    this.router.navigateByUrl("dealerInfo");
  }

  driverPerformance() {
    this.cond = false;
    this.router.navigateByUrl("device-report/Driver-performance");
  }

  route_map() {
    this.router.navigateByUrl("routeMapping");
  }
  trip_report() {
    this.cond = false;
    this.router.navigateByUrl("device-report/trip_report");
  }

  notification() {
    this.cond = false;
    this.router.navigateByUrl("notifications");
  }

  report_speed() {
    this.cond = false;
    localStorage.removeItem("mapLoad_ID");
    this.router.navigateByUrl("device-report/device-speed-report");
  }
  openNav() {
    this.router.navigateByUrl("location");
  }
  geoo() {
    localStorage.removeItem("mapLoad_ID");
    this.router.navigateByUrl("geofencing");
  }
  ideal() {
    localStorage.removeItem("mapLoad_ID");
    this.router.navigateByUrl("device-report/ideal-report");
  }
  cond: Boolean = false;
  /*
  foods = [
    {value: 'Device 1', viewValue: 'Device 1'},
    {value: 'Device 2', viewValue: 'Device 2'},
    
  ]; */

  mainmap: boolean = false;
  speed: any;
  datee: any;
  time: any;
  online: Boolean;
  latLongArr3 = [];
  offline: Boolean = false;
  geo: Boolean = false;
  foods = [];
  devmap(a) {}

  showhistory(a) {
    if (this.new) {
      var selectedDevice = {
        id: this.new.id,
        viewValue: this.new.viewValue,
        iconType: this.new.iconType,
        deviceId: this.new.did,
      };
      this.deviceName = selectedDevice.viewValue;

      this.deviceSelect.push(selectedDevice);

      a = this.deviceSelect[0];
    }

    this.showButton = !this.showButton;

    this.date2 = new Date();
    this.mapp = false;
    this.mappp = false;
    this.MapLoad = false;
    this.historyData = true;
    this.hismap = true;
    this.lcShr = false;
    this.online = false;
    this.offline = true;
    this.latlongObjArr = [];
    this.latLongArr2 = [];
    this.lat = null;
    this.lng = null;

    if (a == undefined) {
    } else {
      this.socket.removeAllListeners(a.deviceId);
      //this.socket_Geo.removeAllListeners(a.did);
    }

    this.latLongArr = [];
  }

  CurrLiveValue: any = null;
  deviceToTrack = [];
  live(b) {
    this.mappp = true;
    this.MapLoad = true;
    this.historyData = false;
    this.SpeedMeter = true;
    this.showButton = true;

    var devId: any;
    if (this.deviceSelect) {
      devId = this.deviceSelect[0].deviceId;
    } else {
      devId = this.new.did;
    }

    if (devId) {
      if (this.navId === undefined || this.navId != "locationHistory") {
        this.livetrack(devId);
      }
    } else {
      if (this.navId === undefined || this.navId != "locationHistory") {
        this.livetrack(null);
      }
    }
  }
  cancells() {
    this.mappp = true;
    this.mapp = true;
    this.lcShr = false;
  }

  speedshow: any;
  location = [];
  historyData: boolean = true;
  //Main Declaration of LiveTrack Function *********************
  livetrack(a) {
    this.markerArray = [];
    var count = 0;
    var that = this;
    this.SpeedMeter2 = false;
    this.PlayData = false;
    this.pauseDate = false;
    var outerThis = this;
    this.mainmap = false;
    if (a == undefined) {
      a = null;
    }

    for (var e = 0; e < this.deviceToTrack.length; e++) {
      //this.socket.removeAllListeners(this.deviceToTrack[e])
    }
    this.deviceToTrack = [];

    for (let i = 0; i < this.foods.length; i++) {
      if (this.foods[i].deviceType == "Tracker") {
        let aTemp = {
          did: this.foods[i].did,
          dname: this.foods[i].viewValue,
        };
        this.device_imei.push(aTemp);

        if (a === null || a === undefined) {
          this.SpeedMeter = false;
          this.mapWidth = "95vw";
          this.deviceToTrack.push(this.foods[i].did);
          this.zoomLevel = 5;
        } else {
          this.SpeedMeter = true;
          this.zoomLevel = 18;
          this.mapWidth = "87vm";
        }
      }
    }
    if (a) {
      this.deviceToTrack.push(a);
    }
  }
  livetrack1(a) {
    this.markerArray = [];
    var count = 0;
    var that = this;
    this.SpeedMeter2 = false;
    this.PlayData = false;
    this.pauseDate = false;
    var outerThis = this;
    this.mainmap = false;
    if (a == undefined) {
      a = null;
    }

    for (var e = 0; e < this.deviceToTrack.length; e++) {
      //this.socket.removeAllListeners(this.deviceToTrack[e])
    }
    this.deviceToTrack = [];

    for (let i = 0; i < this.foods.length; i++) {
      if (this.foods[i].deviceType == "Tracker") {
        let aTemp = {
          did: this.foods[i].did,
          dname: this.foods[i].viewValue,
        };
        this.device_imei.push(aTemp);

        if (a === null || a === undefined) {
          this.SpeedMeter = false;
          this.mapWidth = "95vw";
          this.deviceToTrack.push(this.foods[i].did);
          this.zoomLevel = 5;
        } else {
          this.SpeedMeter = true;
          this.zoomLevel = 18;
          this.mapWidth = "87vm";
        }
      }
    }
    if (a) {
      this.deviceToTrack.push(a);
    }
    this.geoFenceaction(this.device_imei);
    this.online = true;
    this.offline = false;

    this.hismap = false;
    this.mapp = true;
    this.latLongArr = [];

    let map;
    let marker = {};
    let oldChannel = null;
    let delay = 100;
    let target = {};
    let coords = {};
    let ongoingGoToPoint = {};
    let ongoingMoveMarker = {};
    let isMapInit = false;
    let flag;
    let flag2;
    let locations = [];
    // =============== ~animation functions =====================

    var carIcon = {
      // path: car,
      url: "/assets/images/liveTrackIcons/rcar.png",
      scaledSize: new google.maps.Size(50, 50),
      //size: new google.maps.Size(30, 100),
      scale: 0.6,
      strokeColor: "white",
      strokeWeight: 0.1,
      fillOpacity: 1,
      fillColor: "blue",
      //fillColor: '#b75656',
      offset: "5%",
      // rotation: parseInt(heading[i]),
      anchor: new google.maps.Point(25, 25), // orig 10,50 back of car, 10,0 front of car, 10,25 center of car,
      rotation: 0,
    };

    var bikeIcon = {
      // path: bike,
      url: "/assets/images/liveTrackIcons/rbike.png",
      scaledSize: new google.maps.Size(30, 50),
      //size: new google.maps.Size(30, 100),
      scale: 0.6,
      strokeColor: "white",
      strokeWeight: 0.1,
      fillOpacity: 1,
      fillColor: "blue",
      //fillColor: '#b75656',
      offset: "5%",
      // rotation: parseInt(heading[i]),
      anchor: new google.maps.Point(25, 25), // orig 10,50 back of car, 10,0 front of car, 10,25 center of car,
      rotation: 0,
    };

    var jcbIcon = {
      // path: bike,
      url: "/assets/images/liveTrackIcons/idlingjcb.png",
      scaledSize: new google.maps.Size(30, 50),
      //size: new google.maps.Size(30, 100),
      scale: 0.6,
      strokeColor: "white",
      strokeWeight: 0.1,
      fillOpacity: 1,
      fillColor: "blue",
      //fillColor: '#b75656',
      offset: "5%",
      // rotation: parseInt(heading[i]),
      anchor: new google.maps.Point(25, 25), // orig 10,50 back of car, 10,0 front of car, 10,25 center of car,
      rotation: 0,
    };

    var ambulanceIcon = {
      // path: car,
      url: "/assets/images/liveTrackIcons/ambulance_b.png",
      scaledSize: new google.maps.Size(50, 50),
      //size: new google.maps.Size(30, 100),
      scale: 0.6,
      strokeColor: "white",
      strokeWeight: 0.1,
      fillOpacity: 1,
      fillColor: "blue",
      //fillColor: '#b75656',
      offset: "5%",
      // rotation: parseInt(heading[i]),
      anchor: new google.maps.Point(25, 25), // orig 10,50 back of car, 10,0 front of car, 10,25 center of car,
      rotation: 0,
    };

    var truckIcon = {
      // path: truck,
      url: "/assets/images/liveTrackIcons/rtruck.png",
      scaledSize: new google.maps.Size(55, 85),
      //size: new google.maps.Size(30, 100),
      scale: 0.6,
      strokeColor: "white",
      strokeWeight: 0.1,
      fillOpacity: 1,
      fillColor: "blue",
      //fillColor: '#b75656',
      offset: "5%",
      // rotation: parseInt(heading[i]),
      anchor: new google.maps.Point(25, 25), // orig 10,50 back of car, 10,0 front of car, 10,25 center of car,
      rotation: 0,
    };

    var userIcon = {
      // path: user,
      url: "/assets/images/liveTrackIcons/rcar.png",
      scaledSize: new google.maps.Size(30, 50),
      //size: new google.maps.Size(30, 100),
      scale: 0.6,
      strokeColor: "white",
      strokeWeight: 0.1,
      fillOpacity: 1,
      fillColor: "blue",
      //fillColor: '#b75656',
      offset: "5%",
      // rotation: parseInt(heading[i]),
      anchor: new google.maps.Point(25, 25), // orig 10,50 back of car, 10,0 front of car, 10,25 center of car,
      rotation: 0,
    };

    var tractorIcon = {
      url: "/assets/images/liveTrackIcons/rtractor.png",
      scaledSize: new google.maps.Size(35, 50),
      //size: new google.maps.Size(30, 100),
      scale: 0.6,
      strokeColor: "white",
      strokeWeight: 0.1,
      fillOpacity: 1,
      fillColor: "blue",
      //fillColor: '#b75656',
      offset: "5%",
      // rotation: parseInt(heading[i]),
      anchor: new google.maps.Point(25, 25), // orig 10,50 back of car, 10,0 front of car, 10,25 center of car,
      rotation: 0,
    };

    // var rickShawIcon = {
    //   url: '/assets/images/liveTrackIcons/rtractor.png',
    //   scaledSize: new google.maps.Size(35, 50),
    //   //size: new google.maps.Size(30, 100),
    //   scale: .6,
    //   strokeColor: 'white',
    //   strokeWeight: .10,
    //   fillOpacity: 1,
    //   fillColor: 'blue',
    //   //fillColor: '#b75656',
    //   offset: '5%',
    //   // rotation: parseInt(heading[i]),
    //   anchor: new google.maps.Point(25, 25), // orig 10,50 back of car, 10,0 front of car, 10,25 center of car,
    //   rotation: 0
    // };

    // var tempoIcon = {
    //   url: '/assets/images/liveTrackIcons/rtractor.png',
    //   scaledSize: new google.maps.Size(35, 50),
    //   //size: new google.maps.Size(30, 100),
    //   scale: .6,
    //   strokeColor: 'white',
    //   strokeWeight: .10,
    //   fillOpacity: 1,
    //   fillColor: 'blue',
    //   //fillColor: '#b75656',
    //   offset: '5%',
    //   // rotation: parseInt(heading[i]),
    //   anchor: new google.maps.Point(25, 25), // orig 10,50 back of car, 10,0 front of car, 10,25 center of car,
    //   rotation: 0
    // };

    var busIcon = {
      // path: bus,
      url: "/assets/images/liveTrackIcons/rbus.png",
      scaledSize: new google.maps.Size(30, 50),
      //size: new google.maps.Size(30, 100),
      scale: 0.6,
      strokeColor: "white",
      strokeWeight: 0.1,
      fillOpacity: 1,
      fillColor: "blue",
      //fillColor: '#b75656',
      offset: "5%",
      // rotation: parseInt(heading[i]),
      anchor: new google.maps.Point(25, 25), // orig 10,50 back of car, 10,0 front of car, 10,25 center of car,
      rotation: 0,
    };
    var icons = {
      car: carIcon,
      bike: bikeIcon,
      truck: truckIcon,
      tractor: tractorIcon,
      bus: busIcon,
      user: userIcon,
      jcb: jcbIcon,
      ambulance: ambulanceIcon,
    };

    this.flightPathArr = [];
    this.tttttt = [];
    var tempTimeInterval: any;

    coords = {};
    for (var key in ongoingGoToPoint) {
      if (ongoingGoToPoint.hasOwnProperty(key)) {
        clearTimeout(ongoingGoToPoint[key]);
      }
    }

    for (var key in ongoingMoveMarker) {
      if (ongoingMoveMarker.hasOwnProperty(key)) {
        clearTimeout(ongoingMoveMarker[key]);
      }
    }

    for (var x = 0; x < this.deviceToTrack.length; x++) {
      var newChannel = this.deviceToTrack[x].toString();
      var date = new Date().setHours(0, 0, 0, 0);
      //this.socket.on(newChannel, channelListener(newChannel));
      //this.socket.emit('initLive', newChannel, date);
    }

    var r;

    function channelListener(newChannel) {
      return function (msg, initData, deviceInfo) {
        outerThis.tempDevInfo = {};
        outerThis.flightPathArr.push({
          lat: msg.latDecimal,
          lng: msg.longDecimal,
        });
        if (outerThis.enabletrail == true) {
          outerThis.draw_flight_trail(outerThis.flightPathArr);
        }
        outerThis.deviceList.filter(function (dd, index) {
          if (dd.Device_ID === deviceInfo.Device_ID) {
            deviceInfo["checked"] = dd.checked;
          }
        });

        if (outerThis.deviceToTrack.length == 1) {
          outerThis.deviceList.filter(function (colHilight, i) {
            outerThis.deviceList[i]["playPause"] = true;
            if (colHilight.Device_ID === outerThis.deviceToTrack[0]) {
              outerThis.deviceList[i]["columnHighlight"] = true;
              if (msg["GPS positioned"]) {
                outerThis.deviceList[i].gpsTracking = msg["GPS positioned"];
              }
              if (msg.ignition) {
                outerThis.deviceList[i].last_ACC = msg.ignition;
              }
              if (msg.power) {
                outerThis.deviceList[i].power = msg.power;
              }
              if (msg.speed) {
                outerThis.deviceList[i].last_speed = msg.speed;
              }

              if (outerThis.currentPage === 1) {
                outerThis.showSocketData = true;

                outerThis.showSocketData = true;
                // date satellites ignition port
                if (msg.date == undefined) {
                  msg["date"] = colHilight.last_ping_on;
                }

                if (msg.satellites == undefined) {
                  msg["satellites"] = colHilight.satellites;
                }
                if (msg.ignition == undefined) {
                  msg["ignition"] = colHilight.last_ACC;
                }
                if (msg.port == undefined) {
                  msg["port"] = colHilight.port;
                }

                outerThis.socketData = msg;
                outerThis.getSystemLogs(colHilight);
                outerThis.deviceCQ(colHilight);
                outerThis.getRecentNotification(colHilight);
              }
            } else {
              outerThis.deviceList[i]["columnHighlight"] = false;
            }
          });
        }
        this.lat = deviceInfo.last_loc
          ? deviceInfo.last_loc.coordinates[1]
          : null;
        this.lng = deviceInfo.last_loc
          ? deviceInfo.last_loc.coordinates[0]
          : null;

        r = 0;
        if (coords[newChannel] === null || coords[newChannel] === undefined)
          coords[newChannel] = [];
        outerThis.mainmap = true;
        if (
          initData == "ping" ||
          (initData == "initPing" && coords[newChannel].length == 0)
        ) {
          this.latLongArr = [];
          coords[newChannel].splice(0, coords[newChannel].length - 1);
          const speed = parseFloat(msg.speed);
          if (initData == "ping") {
            outerThis.speeed = msg.speed;
          }
          outerThis.MapLoad = false;
          outerThis.test_Data = msg.currentFuel;

          var x = msg.speed;

          const heading = parseFloat(msg.heading);
          const message =
            "IMEI: " + msg.imei + " Speed: " + msg.speed + "Km/hr";
          if (msg.interpolated == null || msg.interpolated === undefined) {
            this.lat = msg.latDecimal;
            this.lng = msg.longDecimal;

            coords[newChannel].push([this.lat, this.lng]);
            let a = {
              lat: msg.latDecimal,
              lng: msg.longDecimal,
              did: msg.imei,
            };

            if (
              a != null &&
              a != undefined &&
              outerThis.navId != "locationComponent"
            ) {
              var geocoder = new google.maps.Geocoder();
              var latlng = new google.maps.LatLng(
                msg.latDecimal,
                msg.longDecimal
              );
            }

            var request = {
              latLng: latlng,
            };

            var latlng_1 = {
              lat: msg.latDecimal,
              long: msg.longDecimal,
            };

            //address function end here
          } else {
            for (let k = 0; k < msg.interpolated.length; k++) {
              if (
                msg.interpolated[k].location.latitude == null ||
                msg.interpolated[k].location.longitude == null
              ) {
                // //console.log("Lattitude Longitude if location.lattitude is null=>",msg.interpolated[k].location.latitude,msg.interpolated[k].location.longitude);
                this.lat = msg.latDecimal;
                this.lng = msg.longDecimal;
                this.titleMarker = message;
                this.titleMarker2 = message;
                this.latLongArr.push([this.lat, this.lng]);
                coords[newChannel].push([this.lat, this.lng]);
                let a = {
                  lat: msg.latDecimal,
                  lng: msg.longDecimal,
                  did: msg.imei,
                };
              } else {
                // //console.log("Lattitude Longitude if location.lattitude is not null=>",msg.interpolated[k].location.latitude,msg.interpolated[k].location.longitude)
                this.lat = msg.interpolated[k].location.latitude;
                this.lng = msg.interpolated[k].location.longitude;
                this.titleMarker = message;
                this.titleMarker2 = message;
                this.latLongArr.push([this.lat, this.lng]);
                coords[newChannel].push([this.lat, this.lng]);
              }

              // converting Address

              var geocoder = new google.maps.Geocoder();
              var latlng = new google.maps.LatLng(
                msg.latDecimal,
                msg.longDecimal
              );

              var request = {
                latLng: latlng,
              };

              var latlng_1 = {
                lat: msg.latDecimal,
                long: msg.longDecimal,
              };
            }
          }

          var boxCheck = deviceInfo.checked;

          if (!isMapInit) {
            //initialize(this.lat, this.lng, newChannel);
          }
          // console.log(boxCheck);

          if (boxCheck === true) {
            initializeMarker(
              that.elementRef,
              this.lat,
              this.lng,
              newChannel,
              deviceInfo.Device_Name,
              deviceInfo.status,
              deviceInfo.status_updated_at,
              deviceInfo.last_ping_on,
              msg,
              initData,
              deviceInfo.iconType,
              deviceInfo
            );
          }

          if (initData == "ping" || status == "RUNNING") {
            if (boxCheck === true) {
              animateMarker(
                that.elementRef,
                marker,
                speed,
                heading,
                true,
                newChannel,
                deviceInfo.Device_Name,
                deviceInfo.status,
                deviceInfo.status_updated_at,
                deviceInfo.last_ping_on,
                msg,
                initData,
                deviceInfo.iconType,
                deviceInfo
              );
            }
          }
          flag = false;
        }
      };
    }

    window.localStorage.shareloc = function (device) {
      this.shareLocation(device);
    };
    function animateMarker(
      elementRef,
      marker,
      km_h,
      heading,
      cancel,
      device,
      deviceName,
      status,
      since,
      lastUpdate,
      msg,
      initData,
      iconType,
      _devInfo
    ) {}
    function animateMarkerOld(
      elementRef,
      marker,
      km_h,
      heading,
      cancel,
      device,
      deviceName,
      status,
      since,
      lastUpdate,
      msg,
      initData,
      iconType,
      _devInfo
    ) {
      var deviceSpeed = status == "STOPPED" ? 0 : msg.speed;

      var lastPing = new Date(_devInfo.last_ping_on).getTime();
      var currTime = new Date().getTime();
      var timediff = currTime - lastPing;
      var oneHourVal = 1 * 60 * 60 * 1000;

      outerThis.last_speed = msg.speed;

      var arrival_time = new Date(since);

      var curr_time = new Date();
      var fd = new Date(arrival_time).getTime();
      var td = curr_time.getTime();
      var timedev_status_difference = td - fd;
      var total_min = timedev_status_difference / 60000;
      var hours = total_min / 60;
      var rhours = Math.floor(hours);
      var minutes = (hours - rhours) * 60;
      var rminutes = Math.round(minutes);
      var Durations = rhours + " " + "hrs" + " " + rminutes + " " + "min";
      if (since == undefined) {
        var deviceData = "";
      } else if (timediff > oneHourVal) {
        var status_toShow = "OUT OF REACH " + "Since " + Durations;
      } else {
        if (status == undefined) {
          var status_toShow = "NA";
        } else {
          var status_toShow = status + " " + "Since" + " " + Durations;
        }

        var deviceData = status_toShow;
      }

      var gsm_signal = "";
      if (msg != undefined) {
        gsm_signal = msg.gsmSignal;
      } else {
        gsm_signal = _devInfo.gsmSignal;
      }

      clearTimeout(ongoingGoToPoint[device]);
      clearTimeout(ongoingMoveMarker[device]);
      var contentString = "";
      if (initData == "initPing") {
        //console.log("Change features");
        var lastLat = _devInfo.last_location.lat;
        var lastlong = _devInfo.last_location.long;
        console.log("INDDDDDDDDDDDDDDDDDDDDDDDDDDDDEH");

        contentString =
          '<div class="infoB">' +
          '<div class="DeviceHead">' +
          '<button style= "position: absolute; left: 0; background: #65889c; color: white; margin-left: 5px;" onclick="window.angularComponentRef.zone.run(() => {window.angularComponentRef.component.addpoi(\'' +
          lastLat +
          "," +
          lastlong +
          "');})\"> add poi </button>" +
          '<p style="margin-bottom: 5px;">' +
          deviceName +
          "</p>" +
          "</div>" +
          '<div class="row rowTwo">' +
          '<div class="col-sm-5">' +
          "Last updated" +
          "</div>" +
          '<div class="col-sm-7 leftPadding">' +
          (lastUpdate
            ? moment(lastUpdate).format("dddd,ll,LTS") +
              " " +
              "(" +
              moment(lastUpdate).fromNow() +
              ")"
            : "No Data Available") +
          "</div>" +
          "</div>" +
          '<div class="row rowOne">' +
          '<div class="col-sm-5">' +
          "GPS Positioned" +
          "</div>" +
          '<div class="col-sm-7 leftPadding">' +
          (_devInfo.gpsTracking == "1"
            ? "Yes"
            : _devInfo.gpsTracking == "0"
            ? "No"
            : "<small>Feature not supported by device</small>") +
          "</div>" +
          "</div>" +
          '<div class="row rowTwo">' +
          '<div class="col-sm-5">' +
          "GPS Signal" +
          "</div>" +
          '<div class="col-sm-7 leftPadding">' +
          (gsm_signal != undefined ? gsm_signal : "NA") +
          "</div>" +
          "</div>" +
          '<div class="row rowOne">' +
          '<div class="col-sm-5">' +
          "Driver's Name" +
          "</div>" +
          '<div class="col-sm-7 leftPadding">' +
          '<p style="margin-bottom:0px">' +
          (outerThis.DriverName ? outerThis.DriverName : "NA") +
          "</p>" +
          "</div>" +
          "</div>" +
          '<div class="row rowOne">' +
          '<div class="col-sm-5">' +
          "Driver's Number" +
          "</div>" +
          '<div class="col-sm-7 leftPadding">' +
          '<p style="margin-bottom:0px">' +
          (outerThis.DriverNumber ? outerThis.DriverNumber : "NA") +
          "</p>" +
          "</div>" +
          "</div>" +
          '<div class="row rowTwo">' +
          '<div class="col-sm-5">' +
          "Last Speed" +
          "</div>" +
          '<div class="col-sm-7 leftPadding">' +
          _devInfo.last_speed +
          " kmph" +
          "</div>" +
          "</div>" +
          '<div class="row rowOne">' +
          '<div class="col-sm-5">' +
          "Status" +
          "</div>" +
          '<div class="col-sm-7 leftPadding">' +
          '<p style="margin-bottom:0px">' +
          deviceData +
          "</p>" +
          "</div>" +
          "</div>";
      } else if (initData == "ping") {
        // //console.log('1', outerThis.liveAdd);
        var lastLat = _devInfo.last_location.lat;
        var lastlong = _devInfo.last_location.long;
        contentString = "";
        contentString =
          '<div class="infoB">' +
          '<div class="DeviceHead">' +
          '<button style="position: absolute; left: 0; background: #65889c; color: white; margin-left: 5px;" onclick="window.angularComponentRef.zone.run(() => {window.angularComponentRef.component.addpoi(\'' +
          lastLat +
          "," +
          lastlong +
          "');})\">add poi</button>" +
          '<p style="margin-bottom: 5px;">' +
          deviceName +
          "</p>" +
          "</div>" +
          '<div class="row rowTwo">' +
          '<div class="col-sm-5">' +
          "Last updated" +
          "</div>" +
          '<div class="col-sm-7 leftPadding">' +
          moment(lastUpdate).format("dddd,ll,LTS") +
          " " +
          "(" +
          moment(lastUpdate).fromNow() +
          ")" +
          "</div>" +
          "</div>" +
          '<div class="row rowOne">' +
          '<div class="col-sm-5">' +
          "GPS Positioned" +
          "</div>" +
          '<div class="col-sm-7 leftPadding">' +
          (_devInfo.gpsTracking == "1"
            ? "Yes"
            : _devInfo.gpsTracking == "0"
            ? "No"
            : "<small>Feature not supported by device</small>") +
          "</div>" +
          "</div>" +
          '<div class="row rowTwo">' +
          '<div class="col-sm-5">' +
          "GPS Signal" +
          "</div>" +
          '<div class="col-sm-7 leftPadding">' +
          (gsm_signal != undefined ? gsm_signal : "NA") +
          "</div>" +
          "</div>" +
          '<div class="row rowOne">' +
          '<div class="col-sm-5">' +
          "Driver's Name" +
          "</div>" +
          '<div class="col-sm-7 leftPadding">' +
          '<p style="margin-bottom:0px">' +
          (outerThis.DriverName ? outerThis.DriverName : "NA") +
          "</p>" +
          "</div>" +
          "</div>" +
          '<div class="row rowOne">' +
          '<div class="col-sm-5">' +
          "Driver's Number" +
          "</div>" +
          '<div class="col-sm-7 leftPadding">' +
          '<p style="margin-bottom:0px">' +
          (outerThis.DriverNumber ? outerThis.DriverNumber : "NA") +
          "</p>" +
          "</div>" +
          "</div>" +
          '<div class="row rowTwo">' +
          '<div class="col-sm-5">' +
          "Speed" +
          "</div>" +
          '<div class="col-sm-7 leftPadding">' +
          deviceSpeed +
          " " +
          "kmph";
        "</div>" +
          "</div>" +
          '<div class="row rowOne">' +
          '<div class="col-sm-5">' +
          "Status" +
          "</div>" +
          '<div class="col-sm-7 leftPadding">' +
          '<p style="margin-bottom:0px">' +
          deviceData +
          "</p>" +
          "</div>" +
          "</div>";
      }

      marker[device]["infowindow"].setContent(contentString);
      console.log("Inside Infowindow");

      function goToPoint() {
        let lat = marker[device].position.lat();
        let lng = marker[device].position.lng();

        let step = (km_h * 1000 * delay) / 3600000; // in meters

        var LTlat_dest: any;
        var LTlng_dest: any;

        if (coords[device].length == 0) {
          LTlat_dest = _devInfo.last_location.lat;
          LTlng_dest = _devInfo.last_location.long;
        } else {
          LTlat_dest = coords[device][target[device]][0];
          LTlng_dest = coords[device][target[device]][1];
        }

        let dest = new google.maps.LatLng(LTlat_dest, LTlng_dest);

        // tslint:disable-next-line:prefer-const
        let distance = google.maps.geometry.spherical.computeDistanceBetween(
          dest,
          marker[device].position
        ); // in meters
        // var heading = google.maps.geometry.spherical.computeHeading(dest, marker[device].position);
        // tslint:disable-next-line:prefer-const
        let numStep = distance / step;
        let i = 0;
        // tslint:disable-next-line:prefer-const
        let deltaLat = (LTlat_dest - lat) / numStep;
        // tslint:disable-next-line:prefer-const
        let deltaLng = (LTlng_dest - lng) / numStep;

        function moveMarker() {
          // console.log("deltaLat",deltaLat,"deltaLng",deltaLng);

          lat += deltaLat;
          lng += deltaLng;

          i += step;
          let markerDOM: any;
          var liveSpeed = parseInt(msg.speed);
          if (i < distance) {
            if (status == "OUT OF REACH") {
              // icons[iconType].url = '/assets/images/liveTrackIcons/outofreach_car.png';
              icons[iconType].url = that.iconSelector(status, iconType, msg);
              markerDOM = elementRef.nativeElement.querySelector(
                "img[src='" + icons[iconType].url + "']"
              );
            } else if (status == "STOPPED") {
              if (liveSpeed >= 1) {
                icons[iconType].url =
                  "/assets/images/liveTrackIcons/running_car.png";
                markerDOM = elementRef.nativeElement.querySelector(
                  "img[src='" + icons[iconType].url + "']"
                );
              } else {
                icons[iconType].url = that.iconSelector(status, iconType, msg);
                markerDOM = elementRef.nativeElement.querySelector(
                  "img[src='" + icons[iconType].url + "']"
                );
              }
            } else if (status == "RUNNING") {
              icons[iconType].url = that.iconSelector(status, iconType, msg);
              markerDOM = elementRef.nativeElement.querySelector(
                "img[src='" + icons[iconType].url + "']"
              );
            } else if (status == "NO DATA") {
              icons[iconType].url = "/assets/image/no_data.png";
              markerDOM = elementRef.nativeElement.querySelector(
                "img[src='" + icons[iconType].url + "']"
              );
            } else if (status == "IDLING") {
              if (liveSpeed >= 1) {
                icons[iconType].url =
                  "/assets/images/liveTrackIcons/running_car.png";
                markerDOM = elementRef.nativeElement.querySelector(
                  "img[src='" + icons[iconType].url + "']"
                );
              } else {
                icons[iconType].url = that.iconSelector(status, iconType, msg);
                markerDOM = elementRef.nativeElement.querySelector(
                  "img[src='" + icons[iconType].url + "']"
                );
              }
            }

            // //console.log(msg.ignition, )
            // _devInfo
            var head = google.maps.geometry.spherical.computeHeading(
              marker[device].getPosition(),
              new google.maps.LatLng(lat, lng)
            );
            // console.log("HEAD__===",head,"Marker==>",marker[device].getPosition(),"LAT LONG=>",new google.maps.LatLng(lat, lng),"==>",lat,lng);

            if (head != 0 || head == NaN) {
              // icons[iconType].rotation = head;
              if (markerDOM) {
                markerDOM.style.transform = "rotate(" + head + "deg)";
              }
            }
            // //console.log("s")

            // //console.log("totalhours=>",thours,_devInfo);

            // ==============================commented on 4-1-2019 =================================
            // //console.log('STATUS1==>',status);
            // if (timediff>oneHourVal) {
            //   icons[iconType].fillColor = "blue";
            // }else  if ((_devInfo.last_ACC == 0) && (msg.speed == 0)) {
            //   icons[iconType].fillColor = "red";
            // } else if ((_devInfo.last_ACC == 1) && (msg.speed > 0)) {
            //   icons[iconType].fillColor = "green";
            // } else if ((_devInfo.last_ACC == 1) && (msg.speed == 0)) {
            //   icons[iconType].fillColor = "yellow";
            // }

            // ==============================commented on 4-1-2019 =================================

            marker[device].setIcon(icons[iconType]);
            marker[device].setPosition(new google.maps.LatLng(lat, lng));
            if (outerThis.deviceToTrack.length == 1)
              map.setCenter({ lat: lat, lng: lng });
            ongoingMoveMarker[device] = setTimeout(moveMarker, delay);
          } else {
            status == "OUT OF REACH";
            if (status == "OUT OF REACH") {
              // icons[iconType].url = '/assets/images/liveTrackIcons/outofreach_car.png';
              icons[iconType].url = that.iconSelector(status, iconType, msg);
              markerDOM = elementRef.nativeElement.querySelector(
                "img[src='" + icons[iconType].url + "']"
              );
            } else if (status == "STOPPED") {
              if (liveSpeed >= 1) {
                icons[iconType].url =
                  "/assets/images/liveTrackIcons/running_car.png";
                markerDOM = elementRef.nativeElement.querySelector(
                  "img[src='" + icons[iconType].url + "']"
                );
              } else {
                icons[iconType].url = that.iconSelector(status, iconType, msg);
                markerDOM = elementRef.nativeElement.querySelector(
                  "img[src='" + icons[iconType].url + "']"
                );
              }
            } else if (status == "RUNNING") {
              // icons[iconType].url = "/assets/images/liveTrackIcons/running_car.png";
              icons[iconType].url = that.iconSelector(status, iconType, msg);
              markerDOM = elementRef.nativeElement.querySelector(
                "img[src='" + icons[iconType].url + "']"
              );
            } else if (status == "NO DATA") {
              icons[iconType].url = "/assets/image/no_data.png";
              markerDOM = elementRef.nativeElement.querySelector(
                "img[src='" + icons[iconType].url + "']"
              );
            } else if (status == "IDLING") {
              if (liveSpeed >= 1) {
                icons[iconType].url =
                  "/assets/images/liveTrackIcons/running_car.png";
                markerDOM = elementRef.nativeElement.querySelector(
                  "img[src='" + icons[iconType].url + "']"
                );
              } else {
                icons[iconType].url = that.iconSelector(status, iconType, msg);
                markerDOM = elementRef.nativeElement.querySelector(
                  "img[src='" + icons[iconType].url + "']"
                );
              }
            }
            // ========================= commented on 1-4-2019 ================================
            // //console.log('STATUS2==>',status);
            // if (timediff>oneHourVal) {
            //   icons[iconType].fillColor = "blue";
            // } else if ((_devInfo == 0) && (msg.speed == 0)) {
            //   icons[iconType].fillColor = "red";
            // } else if ((_devInfo == 1) && (msg.speed > 0)) {
            //   icons[iconType].fillColor = "green";
            // } else if ((_devInfo == 1) && (msg.speed == 0)) {
            //   icons[iconType].fillColor = "yellow";
            // }

            // ========================= commented on 1-4-2019 ================================

            var head = google.maps.geometry.spherical.computeHeading(
              marker[device].getPosition(),
              dest
            );
            // //console.log("head : " + marker[device].getPosition() + ',' + dest)
            if (head != 0 || head == NaN) {
              // icons[iconType].rotation = head
              if (markerDOM) {
                markerDOM.style.transform = "rotate(" + head + "deg)";
              }
            }

            marker[device].setIcon(icons[iconType]);
            marker[device].setPosition(dest);

            if (outerThis.deviceToTrack.length == 1)
              map.setCenter({ lat: LTlat_dest, lng: LTlng_dest });

            target[device] = target[device] + 1;
            if (target[device] === coords[device].length) {
              target[device] = 0;
            } else {
              ongoingGoToPoint[device] = setTimeout(goToPoint, delay);
            }
          }
        }
        //moveMarker();
      }
      ////console.log('The target[device] is %s', target[device]);
      ////console.log('coords[device].length is %s', coords[device].length);
      // do nothing, new points have been added to coords[device]
      // //console.log('coords[device]',coords[device].length);
      // //console.log('coords[device]',coords[device]);
      // //console.log('devinfo',_devInfo);
      // //console.log('coords[device][0][0]coords[device][0][0]coords[device][0][0]',coords[device][0][1]);
      var LTlat: any;
      var LTlng: any;
      // //console.log('_devInfo_devInfo_devInfo', _devInfo);
      if (coords[device].length == 0) {
        LTlat = _devInfo.sec_last_location.lat;
        LTlng = _devInfo.sec_last_location.long;
      } else {
        LTlat = coords[device][0][0];
        LTlng = coords[device][0][1];
      }

      // //console.log('LTlat,LTlng_devInfo',LTlat, LTlng);
      marker[device].setPosition(new google.maps.LatLng(LTlat, LTlng));
      target[device] = 0;
      goToPoint();
    }
    function button() {}

    function initialize(lat, long, device) {
      //   initialize: (lat, long, device)=> {
      if (outerThis.showAddress) {
        console.log(
          "!isMapInit=______________________________________________________________________________________-----------",
          isMapInit
        );

        var latlng_1 = {
          lat: lat,
          long: long,
        };
        outerThis.contactService.getAddressByApi(latlng_1).subscribe((res) => {
          if (res.message == "Address not found in databse") {
            let geocoder = new google.maps.Geocoder();
            let t_latlng = new google.maps.LatLng(lat, long);

            let request = {
              latLng: t_latlng,
            };
            geocoder.geocode(request, function (data, status) {
              if (status == google.maps.GeocoderStatus.OK) {
                if (data[0] != null) {
                  outerThis.liveAdd = data[0].formatted_address;
                } else {
                  outerThis.liveAdd = "N/A";
                }
              }
            });
          } else {
            outerThis.liveAdd = res.address;
          }
          outerThis.showAddress = false;
        });
      }

      // console.log("Lattitude Longitude", lat ,long,device,outerThis.liveAdd);

      if (!isMapInit) {
        var styledMapType = new google.maps.StyledMapType(
          [
            { elementType: "geometry", stylers: [{ color: "#242f3e" }] },
            {
              elementType: "labels.text.stroke",
              stylers: [{ color: "#242f3e" }],
            },
            {
              elementType: "labels.text.fill",
              stylers: [{ color: "#746855" }],
            },
            {
              featureType: "administrative.locality",
              elementType: "labels.text.fill",
              stylers: [{ color: "#d59563" }],
            },
            {
              featureType: "poi",
              elementType: "labels.text.fill",
              stylers: [{ color: "#d59563" }],
            },
            {
              featureType: "poi.park",
              elementType: "geometry",
              stylers: [{ color: "#263c3f" }],
            },
            {
              featureType: "poi.park",
              elementType: "labels.text.fill",
              stylers: [{ color: "#6b9a76" }],
            },
            {
              featureType: "road",
              elementType: "geometry",
              stylers: [{ color: "#38414e" }],
            },
            {
              featureType: "road",
              elementType: "geometry.stroke",
              stylers: [{ color: "#212a37" }],
            },
            {
              featureType: "road",
              elementType: "labels.text.fill",
              stylers: [{ color: "#9ca5b3" }],
            },
            {
              featureType: "road.highway",
              elementType: "geometry",
              stylers: [{ color: "#746855" }],
            },
            {
              featureType: "road.highway",
              elementType: "geometry.stroke",
              stylers: [{ color: "#1f2835" }],
            },
            {
              featureType: "road.highway",
              elementType: "labels.text.fill",
              stylers: [{ color: "#f3d19c" }],
            },
            {
              featureType: "transit",
              elementType: "geometry",
              stylers: [{ color: "#2f3948" }],
            },
            {
              featureType: "transit.station",
              elementType: "labels.text.fill",
              stylers: [{ color: "#d59563" }],
            },
            {
              featureType: "water",
              elementType: "geometry",
              stylers: [{ color: "#17263c" }],
            },
            {
              featureType: "water",
              elementType: "labels.text.fill",
              stylers: [{ color: "#515c6d" }],
            },
            {
              featureType: "water",
              elementType: "labels.text.stroke",
              stylers: [{ color: "#17263c" }],
            },
          ],
          { name: "Styled Map" }
        );

        const myOptions = {
          zoom: outerThis.zoomLevel,
          center: new google.maps.LatLng(lat, long),
          mapTypeId: google.maps.MapTypeId.ROADMAP,
          // styles: [],
          panControl: true,
          // zoomControl: true,
          scaleControl: true,
          // mapTypeControl:true,
          streetViewControl: true,

          overviewMapControl: true,
          rotateControl: true,
          mapTypeControl: true,
          // mapTypeControlOptions: {
          //   style: google.maps.MapTypeControlStyle.DROPDOWN_MENU,
          //   mapTypeIds: ['styled_map']
          // },

          zoomControl: true,
          zoomControlOptions: {
            style: google.maps.ZoomControlStyle.SMALL,
          },
        };

        console.log("manoj 5");
        map = new google.maps.Map(document.getElementById("map"), myOptions);
        map.mapTypes.set("darkmode", styledMapType);
        outerThis.mapNew = map;
        var trafficLayer = new google.maps.TrafficLayer();
        trafficLayer.setMap(map);
        //  outerThis.geoService(map);
        outerThis.trafficLayer = trafficLayer;

        // flight path ==========================

        // =================================================

        // map.mapTypes.set('styled_map', styledMapType);
        // map.setMapTypeId('styled_map');
        // map.setMapTypeId('terrain');
        //  //console.log(map.getCameraPosition().zoom);
        // //console.log("zoom" + map.getZoom());

        // map.setZoom(18);

        google.maps.event.addListener(map, "mousemove", function (event) {
          // //console.log("event" + event);
          displayCoordinates(event.latLng);
        });
        var zoomBar: any;
        zoomBar = document.getElementById("myRange");
        map.setZoom(map.getZoom());

        //zoomBar.max=map.minZoom || 0; zoomBar.min=map.maxZoom||22;
        zoomBar.value = map.getZoom();
        // Update the current slider value (each time you drag the slider handle)
        zoomBar.oninput = function () {
          //console.log("inside zoombar Value");
          map.setZoom(parseInt(this.value));
        };

        google.maps.event.addListener(map, "zoom_changed", function (event) {
          // //console.log("event" + event);
          // //console.log(map.getZoom());
          if (zoomBar.value) zoomBar.value = map.getZoom();
        });

        /*          var controlMarkerUI = document.createElement('div');
                 controlMarkerUI.style.cursor = 'pointer';
                 controlMarkerUI.style.backgroundImage = "url(../../assets/image/history.png)";
                 controlMarkerUI.style.height = '28px';
                 controlMarkerUI.style.width = '38px';
                 controlMarkerUI.title = 'History';
                 
                 map.controls[google.maps.ControlPosition.TOP_RIGHT].push(controlMarkerUI);
                 
                 controlMarkerUI.addEventListener('click', ()=>{
           
                 }); */

        /*            var controlTrashUI = document.createElement('div');
                 controlTrashUI.style.cursor = 'pointer';
                  controlTrashUI.style.backgroundImage = "url(../../assets/image/share.png)";
                  controlTrashUI.style.height = '28px';
                  controlTrashUI.style.width = '38px';
    
                  controlTrashUI.title = 'Share';
                  map.controls[google.maps.ControlPosition.RIGHT_TOP].push(controlTrashUI);
                  controlTrashUI.addEventListener('click', function(e){
                    //console.log("Share Calling...")
                  }); */
      }

      isMapInit = true;
      flag2 = true;
      outerThis.getDevicebyId();
    }

    function displayCoordinates(pnt) {
      var latitudeInDMS, longitudeInDMS;
      //lat in DMS string format
      latitudeInDMS = ConvertDDToDMS(pnt.lat(), false);
      outerThis.latitudeInDMS =
        latitudeInDMS.dir +
        " " +
        latitudeInDMS.deg +
        "° " +
        latitudeInDMS.min +
        "' " +
        latitudeInDMS.sec +
        "''";
      //lon in DMS string format
      longitudeInDMS = ConvertDDToDMS(pnt.lng(), true);
      outerThis.longitudeInDMS =
        longitudeInDMS.dir +
        " " +
        longitudeInDMS.deg +
        "° " +
        longitudeInDMS.min +
        "' " +
        longitudeInDMS.sec +
        "''";

      // //console.log(outerThis.latitudeInDMS + "-" + outerThis.longitudeInDMS);
    }

    function ConvertDDToDMS(D, lng) {
      return {
        dir: D < 0 ? (lng ? "W" : "S") : lng ? "E" : "N",
        deg: 0 | (D < 0 ? (D = -D) : D),
        min: 0 | ((D % 1) * 60),
        sec: (0 | (((D * 60) % 1) * 6000)) / 100,
      };
    }

    function toggleGeofence(choice) {
      // //console.log(choice);
      if (choice) {
        outerThis.geoService(map);
      } else {
        outerThis.removeGeofence();
        outerThis.enableGeofenceComponent = !outerThis.enableGeofenceComponent;
      }
    }

    this.toggleGeofence = toggleGeofence;
    var routePath;
    var flightPath;
    var allSourceDestinationMarkers = [];
    var poiMarkers = [];
    var allRoutePathPoints = [];
    function routeDetails(uId, choice) {
      // //console.log(uId);

      if (choice) {
        outerThis.contactService.getRouteDetail_path(uId).subscribe((res) => {
          // //console.log("abcd2", res)
          routePath = res;
          showRoutes();
          outerThis.enableRouteComponent = !outerThis.enableRouteComponent;
        });
      } else {
        //removing Route source destination markers
        for (var i = 0; i < allSourceDestinationMarkers.length; i++) {
          allSourceDestinationMarkers[i].setMap(null);
        }
        allSourceDestinationMarkers = [];
        //removing Route points
        for (var i = 0; i < allRoutePathPoints.length; i++) {
          allRoutePathPoints[i].setMap(null);
        }
        allRoutePathPoints = [];
        outerThis.enableRouteComponent = !outerThis.enableRouteComponent;
      }
    }

    var mapData, poiData;
    var marker1;
    this.routeDetails = routeDetails;
    function showRoutes() {
      // //console.log(routePath[1].path);
      //["skyblue","green","purple","orange","darkblue","yellow","red"]
      let colors = [
        "1E90FF",
        "28B463",
        "6C3483",
        "D35400",
        "2C3E50",
        "F1C40F",
        "E74C3C",
      ];
      for (var j = 0; j < routePath.length; j++) {
        //outerThis.dataArrayCoords = [];
        mapData = [];
        for (var i = 0; i < routePath[j].path.length; i++) {
          var arr = [];
          arr.push(routePath[j].path[i].location.coordinates[1]);
          arr.push(routePath[j].path[i].location.coordinates[0]);
          //outerThis.dataArrayCoords.push(arr);

          mapData.push({
            lat: routePath[j].path[i].location.coordinates[1],
            lng: routePath[j].path[i].location.coordinates[0],
          });
        }

        ////console.log(outerThis.dataArrayCoords);

        // //console.log(mapData[0]);
        // //console.log(mapData[mapData.length - 1]);

        var colorForPath = colors[j % colors.length];
        var strokeColor = "#" + colorForPath;
        // //console.log("j:" + j + "Color:" + strokeColor + " deno:" + (colors.length - 1) + "nume:" + (j + 1));

        var sourceIcon =
          "http://www.googlemapsmarkers.com/v1/S/" +
          "009933" +
          "/FFFFFF/000000/ "; //colorForPath
        var pinImage = new google.maps.MarkerImage(sourceIcon);
        marker = new google.maps.Marker({
          position: mapData[0],
          map: map,
          icon: pinImage,
          title: "Source",
        });
        allSourceDestinationMarkers.push(marker);
        console.log(allSourceDestinationMarkers);

        var destinationIcon =
          "http://www.googlemapsmarkers.com/v1/D/" +
          "FF3300" +
          "/FFFFFF/000000/ "; //colorForPath
        var pinImage1 = new google.maps.MarkerImage(destinationIcon);
        marker1 = new google.maps.Marker({
          position: mapData[mapData.length - 1],
          map: map,
          icon: pinImage1,
          title: "Destination",
        });
        allSourceDestinationMarkers.push(marker1);

        flightPath = new google.maps.Polyline({
          path: mapData,
          geodesic: true,
          strokeColor: strokeColor,
          strokeOpacity: 1.0,
          strokeWeight: 6,
        });
        allRoutePathPoints.push(flightPath);
        // //console.log(mapData);
        flightPath.setMap(map);
        // //console.log(flightPath);
      }
    }

    function togglePOI(choice) {
      // //console.log(choice);
      if (choice) {
        getPOIs(this.useridd);
      } else {
        removePOIs();
        outerThis.enablePOIComponent = !outerThis.enablePOIComponent;
      }
    }

    this.togglePOI = togglePOI;

    var pois = [];
    function getPOIs(uId) {
      outerThis.contactService.getPOI(uId).subscribe((res) => {
        // //console.log("pois", res)
        pois = res;
        plotAllPOIs();
        outerThis.enablePOIComponent = !outerThis.enablePOIComponent;
      });
    }

    function removePOIs() {
      for (var i = 0; i < poiMarkers.length; i++) {
        poiMarkers[i].setMap(null);
      }
      poiMarkers = [];
    }

    function plotAllPOIs() {
      console.log("PLOTING POIIIISISISISI");

      for (var i = 0; i < pois.length; i++) {
        //var arr = [];
        poiData = [];
        //arr.push(pois[i].poi.location.coordinates[1]);
        //arr.push(pois[i].poi.location.coordinates[0]);

        poiData.push({
          lat: pois[i].poi.location.coordinates[1],
          lng: pois[i].poi.location.coordinates[0],
        });

        var poiIcon = "/assets/images/liveTrackIcons/building.jpg";
        // var poiIcon="https://img.icons8.com/ios-filled/50/000000/building-with-rooftop-terrace.png"
        // building.jpeg
        // var poiIcon = "https://developers.google.com/maps/documentation/javascript/examples/full/images/beachflag.png";
        //"http://www.googlemapsmarkers.com/v1/P/" + "000000" + "/FFFFFF/000000/ ";//'/assets/images/poi.png';//colorForPath
        var poiImage = new google.maps.MarkerImage(poiIcon);
        marker = new google.maps.Marker({
          position: poiData[0],
          map: map,
          icon: poiImage,
          title: pois[i].poi.poiname,
        });
        poiMarkers.push(marker);

        var infobox_numberPlate = new InfoBox({
          content:
            "<div class='infobox' style='padding:2px;background:#575656;margin-left: -25px;'><small><b style='color: #ffffff;font-weight:300;font-size:12px;'>" +
            pois[i].poi.poiname +
            "</b></small></div>",
          disableAutoPan: false,
          maxWidth: 150,
          alignBottom: true,
          pixelOffset: new google.maps.Size(-25, -20),
          zIndex: null,
          boxStyle: {
            opacity: 1,
            zIndex: 999,
            width: "auto",
            padding: "2px",
          },
          closeBoxURL: "",
          infoBoxClearance: new google.maps.Size(1, 1),
        });

        infobox_numberPlate.open(map, marker);

        //   var infoWindow = new google.maps.InfoWindow;

        // var contentString = '<b>'+pois[i].poi.poiname+'</b>'
        // infoWindow.setContent(contentString);
        // infoWindow.setPosition(poiData[0]);

        // infoWindow.open(map);
      }
    }

    function dayClick() {
      // //console.log("fdf");
      this.showhistory();
    }
    function initializeMarker(
      elementRef,
      lat,
      long,
      device,
      deviceName,
      status,
      since,
      lastUpdatedTime,
      msg,
      initData,
      iconType,
      _devInfo
    ) {}
    function initializeMarkerOld(
      elementRef,
      lat,
      long,
      device,
      deviceName,
      status,
      since,
      lastUpdatedTime,
      msg,
      initData,
      iconType,
      _devInfo
    ) {
      // //console.log("Initialize marker called");
      // //console.log("Vehicle Speed",msg.speed);

      outerThis.latToPass = lat;
      outerThis.longToPass = long;

      // ======================================Converting Address==============================================================
      var liveAddress = "";
      var arrival_time = new Date(since);
      var curr_time = new Date();
      var fd = new Date(arrival_time).getTime();
      var td = curr_time.getTime();
      var timedev_status_difference = td - fd;
      var total_min = timedev_status_difference / 60000;
      var hours = total_min / 60;
      var rhours = Math.floor(hours);
      var minutes = (hours - rhours) * 60;
      var rminutes = Math.round(minutes);

      var Durations = rhours + " " + "hrs" + " " + rminutes + " " + "min";
      if (since == undefined) {
        var deviceData = "";
      } else {
        if (status == undefined) {
          var status_toShow = "NA";
        } else {
          var status_toShow = status + " " + "Since" + " " + Durations;
        }

        var deviceData = status_toShow;
      }

      console.log(marker[device]);
      console.log(marker);
      if (marker[device] == null || marker[device] == undefined) {
        //  var lastPing = new Date(_devInfo.last_ping_on).getTime();
        //  var currTime = new Date().getTime();
        //  var timediff = currTime-lastPing;
        //  var totMin =timediff / 60000;
        //  var tothours =totMin/60;
        //  var thours = Math.floor(tothours);
        //  //console.log('totalHours=>',thours);
        // ==================================================below code commented on 15-may-2019 ===============================
        // if((icons[iconType] != null)||(icons[iconType] != undefined)){
        //   if (status == "OUT OF REACH") {
        //     icons[iconType].fillColor = "blue";
        //   }else if (status == "STOPPED") {
        //     icons[iconType].fillColor = "red";
        //   } else if (status == "RUNNING") {
        //     icons[iconType].fillColor = "green";
        //   } else if (status == "IDLING") {
        //     icons[iconType].fillColor = "yellow";
        //   }
        // }

        // ==================================================above code commented on 15-may-2019 ===============================

        let markerDOM: any;

        if (icons[iconType] != null || icons[iconType] != undefined) {
          if (status == "OUT OF REACH") {
            icons[iconType].url = that.iconSelector(status, iconType, msg);

            // markerDOM = elementRef.nativeElement.querySelector("img[src='/assets/images/liveTrackIcons/outofreach_car.png']");
          } else if (status == "STOPPED") {
            icons[iconType].url = that.iconSelector(status, iconType, msg);

            // markerDOM = elementRef.nativeElement.querySelector("img[src='/assets/images/liveTrackIcons/stopped_car.png']");
          } else if (status == "RUNNING") {
            icons[iconType].url = that.iconSelector(status, iconType, msg);

            // markerDOM = elementRef.nativeElement.querySelector("img[src='/assets/images/liveTrackIcons/running_car.png']");
          } else if (status == "NO DATA") {
            icons[iconType].url = that.iconSelector(status, iconType, msg);

            // markerDOM = elementRef.nativeElement.querySelector("img[src='/assets/images/liveTrackIcons/running_car.png']");
          } else if (status == "IDLING") {
            icons[iconType].url = that.iconSelector(status, iconType, msg);

            // markerDOM = elementRef.nativeElement.querySelector("img[src='/assets/images/liveTrackIcons/idle_car.png']");
          }
        }
        // ==========================commented on 4-1-2019 ==========================
        // if (timediff>oneHourVal) {
        //   icons[iconType].fillColor = "blue";
        // }else if ((_devInfo.last_ACC == 0) && (msg.speed == 0)) {
        //   icons[iconType].fillColor = "red";
        // } else if ((_devInfo.last_ACC == 1) && (msg.speed > 0)) {
        //   icons[iconType].fillColor = "green";
        // } else if ((_devInfo.last_ACC == 1) && (msg.speed == 0)) {
        //   icons[iconType].fillColor = "yellow";
        // }
        // ==========================commented on on 4-1-2019==========================

        var m = new google.maps.Marker({
          position: new google.maps.LatLng(lat, long),
          map: map,
          icon: icons[iconType],
        });

        // var mtemp = {
        //   marker : m,
        //   // imei: _devInfo,
        //   icon :icons[iconType],
        //   lat: lat,
        //   lng:long
        // }
        // outerThis.markerArray.push(mtemp);
        //console.log('marker Temp array=>',outerThis.markerArray);

        // var sec_last_lat = _devInfo.sec_last_location?_devInfo.sec_last_location.lat:null;
        // var sec_last_lng = _devInfo.sec_last_location?_devInfo.sec_last_location.long:null;
        var Initial_head = _devInfo ? parseFloat(_devInfo.heading) : 0;
        // var Initial_head = google.maps.geometry.spherical.computeHeading(new google.maps.LatLng(sec_last_lat,sec_last_lng),new google.maps.LatLng(lat,long));
        //console.log('Initial_head',Initial_head);

        if (count == 0) {
          var marker_init = setTimeout(function () {
            var markerDOM_temp = that.elementRef.nativeElement.querySelector(
              "img[src='" + icons[iconType].url + "']"
            );
            if (markerDOM_temp) {
              markerDOM_temp.style.transform =
                "rotate(" + Initial_head + "deg)";
              count = 1;
              clearTimeout(marker_init);
            }
          }, 2000);
        }
        var infobox_numberPlate;
        if (outerThis.showLabels) {
          console.log("HOWWWWWWWWWWW");

          infobox_numberPlate = new InfoBox({
            content:
              "<div class='infobox' style='padding:2px;background:#575656;margin-left: -25px;'><small><b style='color: #ffffff;font-weight:300;font-size:12px;'>" +
              deviceName +
              "</b></small></div>",
            disableAutoPan: false,
            maxWidth: 150,
            alignBottom: true,
            pixelOffset: new google.maps.Size(-25, -20),
            zIndex: null,
            boxStyle: {
              opacity: 1,
              zIndex: 999,
              width: "auto",
              padding: "2px",
            },
            closeBoxURL: "",
            infoBoxClearance: new google.maps.Size(1, 1),
          });
        } else {
          console.log("NHOWWWWWWWWWWW");
          infobox_numberPlate = new InfoBox({
            content: "",
            disableAutoPan: false,
            maxWidth: 150,
            alignBottom: true,
            pixelOffset: new google.maps.Size(-25, -20),
            zIndex: null,
            boxStyle: {
              opacity: 1,
              zIndex: 999,
              width: "auto",
              padding: "2px",
            },
            closeBoxURL: "",
            infoBoxClearance: new google.maps.Size(1, 1),
          });
        }

        locations.push(m);
        // infobox_numberPlate.open(map, m);
        infobox_numberPlate.open(map, m);
        var gsm_signal = "";
        if (msg != undefined) {
          gsm_signal = msg.gsmSignal;
        } else {
          gsm_signal = _devInfo.gsmSignal;
        }

        //m['infowindow'] = new google.maps.InfoWindow();
        var contentString = "";
        if (initData == "initPing") {
          contentString =
            '<div class="infoB">' +
            '<div class="DeviceHead">' +
            '<button style="position: absolute; left: 0; background: #65889c; color: white; margin-left: 5px;" onclick="window.angularComponentRef.zone.run(() => {window.angularComponentRef.component.addpoi(\'' +
            lat +
            "," +
            long +
            "');})\"> add poi </button>" +
            '<p style="margin-bottom: 5px;">' +
            deviceName +
            "</p>" +
            "</div>" +
            '<div class="row rowTwo">' +
            '<div class="col-sm-5">' +
            "Last updated" +
            "</div>" +
            '<div class="col-sm-7 leftPadding">' +
            (lastUpdatedTime
              ? moment(lastUpdatedTime).format("dddd,ll,LTS") +
                " " +
                "(" +
                moment(lastUpdatedTime).fromNow() +
                ")"
              : "No Data Available") +
            "</div>" +
            "</div>" +
            '<div class="row rowOne">' +
            '<div class="col-sm-5">' +
            "GPS Positioned" +
            "</div>" +
            '<div class="col-sm-7 leftPadding">' +
            (_devInfo.gpsTracking == "1"
              ? "Yes"
              : _devInfo.gpsTracking == "0"
              ? "No"
              : "<small>Feature not supported by device</small>") +
            "</div>" +
            "</div>" +
            '<div class="row rowTwo">' +
            '<div class="col-sm-5">' +
            "GPS Signal" +
            "</div>" +
            '<div class="col-sm-7 leftPadding">' +
            (gsm_signal != undefined ? gsm_signal : "NA") +
            "</div>" +
            "</div>" +
            '<div class="row rowOne">' +
            '<div class="col-sm-5">' +
            "Driver's Name" +
            "</div>" +
            '<div class="col-sm-7 leftPadding">' +
            '<p style="margin-bottom:0px">' +
            (outerThis.DriverName ? outerThis.DriverName : "NA") +
            "</p>" +
            "</div>" +
            "</div>" +
            '<div class="row rowOne">' +
            '<div class="col-sm-5">' +
            "Driver's Number" +
            "</div>" +
            '<div class="col-sm-7 leftPadding">' +
            '<p style="margin-bottom:0px">' +
            (outerThis.DriverNumber ? outerThis.DriverNumber : "NA") +
            "</p>" +
            "</div>" +
            "</div>" +
            '<div class="row rowTwo">' +
            '<div class="col-sm-5">' +
            "Last Speed" +
            "</div>" +
            '<div class="col-sm-7 leftPadding">' +
            _devInfo.last_speed +
            " kmph" +
            "</div>" +
            "</div>" +
            '<div class="row rowOne">' +
            '<div class="col-sm-5">' +
            "Status" +
            "</div>" +
            '<div class="col-sm-7 leftPadding">' +
            '<p style="margin-bottom:0px">' +
            deviceData +
            "</p>" +
            "</div>" +
            "</div>";

          // '<div class="row" id="viewParanoma">'+
          // '<div class="col-sm-12">'+
          // '<p>'+'StreetView Content'+'</p>'+
          // +'</div></div>'

          // '<button onclick="window.angularComponentRef.zone.run(() => {window.angularComponentRef.component.addpoi(\'' + lat + ',' + long + '\');})"> add poi </button>'
        } else if (initData == "ping") {
          // //console.log('statusdeviceSpeeddeviceSpeeddeviceSpeeddeviceSpeed=>',speed);
          outerThis.last_speed = msg.speed;
          contentString = "";
          contentString =
            '<div class="infoB">' +
            '<div class="DeviceHead">' +
            '<button style="position: absolute; left: 0; background: #65889c; color: white; margin-left: 5px;" onclick="window.angularComponentRef.zone.run(() => {window.angularComponentRef.component.addpoi(\'' +
            lat +
            "," +
            long +
            "');})\">add poi</button>" +
            '<p style="margin-bottom: 5px;">' +
            deviceName +
            "</p>" +
            "</div>" +
            '<div class="row rowTwo">' +
            '<div class="col-sm-5">' +
            "Last updated" +
            "</div>" +
            '<div class="col-sm-7 leftPadding">' +
            (lastUpdatedTime
              ? moment(lastUpdatedTime).format("dddd,ll,LTS") +
                " " +
                "(" +
                moment(lastUpdatedTime).fromNow() +
                ")"
              : "No Data Available") +
            "</div>" +
            "</div>" +
            '<div class="row rowOne">' +
            '<div class="col-sm-5">' +
            "GPS Positioned" +
            "</div>" +
            '<div class="col-sm-7 leftPadding">' +
            (_devInfo.gpsTracking == "1"
              ? "Yes"
              : _devInfo.gpsTracking == "0"
              ? "No"
              : "<small>Feature not supported by device</small>") +
            "</div>" +
            "</div>" +
            '<div class="row rowTwo">' +
            '<div class="col-sm-5">' +
            "GPS Signal" +
            "</div>" +
            '<div class="col-sm-7 leftPadding">' +
            (gsm_signal != undefined ? gsm_signal : "NA") +
            "</div>" +
            "</div>" +
            '<div class="row rowOne">' +
            '<div class="col-sm-5">' +
            "Driver's Name" +
            "</div>" +
            '<div class="col-sm-7 leftPadding">' +
            '<p style="margin-bottom:0px">' +
            (outerThis.DriverName ? outerThis.DriverName : "NA") +
            "</p>" +
            "</div>" +
            "</div>" +
            '<div class="row rowOne">' +
            '<div class="col-sm-5">' +
            "Driver's Number" +
            "</div>" +
            '<div class="col-sm-7 leftPadding">' +
            '<p style="margin-bottom:0px">' +
            (outerThis.DriverNumber ? outerThis.DriverNumber : "NA") +
            "</p>" +
            "</div>" +
            "</div>" +
            '<div class="row rowTwo">' +
            '<div class="col-sm-5">' +
            "Speed" +
            "</div>" +
            '<div class="col-sm-7 leftPadding">' +
            outerThis.last_speed +
            " " +
            "kmph";
          "</div>" +
            "</div>" +
            '<div class="row rowOne">' +
            '<div class="col-sm-5">' +
            "Status" +
            "</div>" +
            '<div class="col-sm-7 leftPadding">' +
            '<p style="margin-bottom:0px">' +
            deviceData +
            "</p>" +
            "</div>" +
            "</div>";

          // '<div class="row" id="viewParanoma">'+
          // '<div class="col-sm-12">'+
          // '<p>'+'StreetView Content'+'</p>'+
          // +'</div></div>'

          // '<button onclick="window.angularComponentRef.zone.run(() => {window.angularComponentRef.component.addpoi(\'' + lat + ',' + long + '\');})">add poi</button>'
        }

        var myOptions = {
          content: contentString,
          disableAutoPan: false,

          maxWidth: 0,
          pixelOffset: new google.maps.Size(-18, -25),
          zIndex: null,
          boxStyle: {
            //background: "url('https://raw.githubusercontent.com/googlemaps/v3-utility-library/master/infobox/examples/tipbox.gif') no-repeat"
            // ,
            opacity: 0.8,
            // , width: "380px"
            // , padding: "10px"
            // , "background-color" : "white"
          },
          closeBoxMargin: "10px 5px 3px 3px",
          closeBoxURL: "/assets/image/close.png",
          infoBoxClearance: new google.maps.Size(10, 10),
          isHidden: false,
          pane: "floatPane",
          enableEventPropagation: true,
          alignBottom: true,
        };
        m["infowindow"] = new InfoBox(myOptions);
        //console.log("Infowindow card",m);

        var mtemp = {
          marker: m,
          imei: _devInfo.Device_ID,
          icon: icons[iconType],
          lat: lat,
          lng: long,
          infowindow: new InfoBox(myOptions),
          number_plate: infobox_numberPlate,
        };
        outerThis.markerArray.push(mtemp);
        console.log(
          "marker Temp array=>",
          outerThis.markerArray,
          outerThis.socketData
        );
        google.maps.event.addListener(m, "click", function () {
          //console.log('Opening Infow window',m);
          // { lat: , lng: }
          var fenway = { lat: m.position.lat(), lng: m.position.lng() };
          // //console.log("latlnglitrals",m.position.lat(),m.position.lng());
          //console.log(fenway);
          var panorama = new google.maps.StreetViewPanorama(
            document.getElementById("viewParanoma"),
            {
              position: fenway,
              pov: {
                heading: 34,
                pitch: 10,
              },
            }
          );
          map.setStreetView(panorama);
          //console.log('111111111111111111111111111111111111111111111111111=>',this)
          this["infowindow"].open(map, this);
        });
        marker[device] = m;
        target[device] = 0;
      }
      //  //console.log(locations)
      var z = locations;
    }

    //  this.togglePOI(true);
  }
  flightPathArr: any = [];
  isTraffic: boolean = true;
  mapTypeId: any = "roadmap";
  setMapType(mapTypeId) {
    // //console.log(mapTypeId);
    this.darkModeSwitch = false;

    if (mapTypeId == "traffic") {
      this.isTraffic = !this.isTraffic;
      if (this.isTraffic) {
        this.trafficLayer.setMap(this.mapNew);
      } else {
        this.trafficLayer.setMap(null);
      }
    } else {
      this.mapTypeId = mapTypeId;
      if (mapTypeId === "darkmode") {
        this.darkModeSwitch = true;
      }
      this.mapNew.setMapTypeId(mapTypeId);
    }
  }

  enableRouteComponent = false;
  enableGeofenceComponent = false;
  enablePOIComponent = false;
  mapComponetButton;
  mapButtonToggle(option) {
    if (option == "geofencing") {
      this.enableGeofenceComponent = !this.enableGeofenceComponent;
      this._openMapComponet.geofenceAction(this.enableGeofenceComponent);
    }
  }

  getAddressBy(msg, deviceInfo, isForce = false) {
    let outerThis = this;
    if (isForce || outerThis.navId != "locationComponent") {
      outerThis.liveAdd = "";

      let d_lat = msg.latDecimal
        ? msg.latDecimal
        : deviceInfo.last_loc
        ? deviceInfo.last_loc.coordinates[1]
        : null;
      let d_lng = msg.longDecimal
        ? msg.longDecimal
        : deviceInfo.last_loc
        ? deviceInfo.last_loc.coordinates[0]
        : null;

      var latlng_1 = {
        lat: d_lat,
        long: d_lng,
      };
      outerThis.contactService.getAddressByApi(latlng_1).subscribe((res) => {
        if (res.message == "Address not found in databse") {
          let geocoder = new google.maps.Geocoder();
          let t_latlng = new google.maps.LatLng(d_lat, d_lng);

          let request = {
            latLng: t_latlng,
          };
          geocoder.geocode(request, function (data, status) {
            if (status == google.maps.GeocoderStatus.OK) {
              if (data[0] != null) {
                outerThis.liveAdd = data[0].formatted_address;
                // //console.log(outerThis.liveAdd);
                outerThis.saveAddress(d_lat, d_lng, outerThis.liveAdd);
              } else {
                // //console.log("No address available")
                outerThis.liveAdd = "No address available";
              }
            } else {
              outerThis.liveAdd = "NA";
            }
          });
        } else {
          outerThis.liveAdd = res.address;
        }
        console.log("ADDRESS---->", outerThis.liveAdd);
      });
    }
  }

  toggleMapComponents(option) {
    if (this.showHistory) {
      if (option == "route") {
        //route,pointofinterest,geofencing
        this.routeDetails1(this.useridd, !this.enableRouteComponent);
      } else if (option == "geofencing") {
        this.toggleGeofence1(!this.enableGeofenceComponent);
      } else if (option == "pointofinterest") {
        // //console.log(option);
        this.togglePOI1(!this.enablePOIComponent);
      }
    } else {
      if (option == "route") {
        //route,pointofinterest,geofencing
        this.routeDetails(this.useridd, !this.enableRouteComponent);
      } else if (option == "geofencing") {
        this.toggleGeofence(!this.enableGeofenceComponent);
      } else if (option == "pointofinterest") {
        // //console.log(option);
        this.togglePOI(!this.enablePOIComponent);
      }
    }
    //var useridd = JSON.parse(window.atob(window.localStorage.token.split('.')[1]))._id;
  }

  allGeofencePolygon = [];
  geoService(map) {
    this.contactService.getGeoFence(this.useridd).subscribe((data) => {
      this.devicess = data;

      for (let i = 0; i < this.devicess.length; i++) {
        let cordin = [];

        let a = this.devicess[i].geofence.coordinates[0];

        for (let k = 0; k < a.length; k++) {
          let b = {
            lat: a[k][1],
            lng: a[k][0],
          };
          cordin.push(b);
        }
        this.geofence(cordin, this.devicess[i].geoname, map);
      }
      this.enableGeofenceComponent = !this.enableGeofenceComponent;
    });
  }

  geofence(zzz, yyy, map) {
    var infoWindow;
    var outerThis = this;
    var GeoFencCoords = zzz;
    var GeoName = yyy;

    ////console.log(GeoFencCoords)
    plotGeoFence(GeoFencCoords);
    function plotGeoFence(GeoFencCoords) {
      var bermudaTriangle = new google.maps.Polygon({
        paths: GeoFencCoords,
        strokeColor: "#FF0000",
        strokeOpacity: 0.8,
        strokeWeight: 3,
        fillColor: "#FF0000",
        fillOpacity: 0.35,
      });
      bermudaTriangle.setMap(map);

      outerThis.allGeofencePolygon.push(bermudaTriangle);
      bermudaTriangle.addListener("click", showArrays);

      infoWindow = new google.maps.InfoWindow();
    }

    /** @this {google.maps.Polygon} */
    function showArrays(event) {
      var vertices = this.getPath();

      var contentString = "<b>Geo Fence</b><br>" + "Name: " + GeoName;

      infoWindow.setContent(contentString);
      infoWindow.setPosition(event.latLng);

      infoWindow.open(map);
    }
  }

  removeGeofence() {
    for (var i = 0; i < this.allGeofencePolygon.length; i++) {
      this.allGeofencePolygon[i].setMap(null);
    }
    this.allGeofencePolygon = [];
  }

  // Outside Function declaration
  ongoingGoToPoint: any;
  ongoingMoveMarker: any;
  isMapInit: any;
  marker: any;
  map2load: Boolean = false;

  geofun: Boolean = false;
  date1: any = new Date();
  date2: any = new Date();
  interpolated: any;
  Load: Boolean = false;
  Load2: Boolean = false;

  showHideClusters() {
    // //console.log("Show hide clusters")
  }
  last_pointer: any;
  SpeedMeter2: boolean = false;
  speeed2: any = 0;
  PlayData: boolean = false;
  pauseDate: boolean = false;
  inter(b) {
    // //console.log(b);
    if (b == "fast") {
      this.speed = 2 * this.speed;
      // //console.log(this.speed)
    } else if (b == "slow") {
      if (this.speed > 50) {
        this.speed = this.speed / 2;
        // //console.log(this.speed)
      } else {
        /*  this.speed =200 */
      }
    } else {
      this.speed = 200;
    }
    //this.play(null)
  }
  // play(a) {

  animateMarker_history(marker, coords, km_h, iconType) {
    this.cummulative_Distance = 0;
    var ongoingMoveMarker = null;
    this.SpeedMeter2 = true;

    this.PlayData = true;
    // this.playingHistory = true;
    this.historyMap.setZoom(15);
    if (km_h == 0 || km_h == "0") {
      km_h = 50;
    }
    var map, marker;
    var coord = this.dataArrayCoords[0];
    this.playingHistory = true;

    var lat = coord[0];
    // //console.log(lat);
    var lng = coord[1];
    let outerThis = this;
    var startPos = [lat, lng];
    this.speed = 200;
    var iconselected = this.devicon;
    var delay = 100;

    var that = this;

    var contentString;

    map = this.historyMap;

    var target = 0;
    // if(this.rangeDetector == true){
    //   target = this.indexValue;
    // }
    // this.rangeDetector=false;
    var km_h = km_h || 50;

    if (!startPos.length) coords.push([startPos[0], startPos[1]]);

    that.goToPoint = function () {
      // //console.log("Go to point function");
      if (that.rangeDetector === true) {
        a = that.indexValue;
        target = that.indexValue;
        that.sliderValue = that.indexValue;
      }
      var lat = marker.position.lat();
      var lng = marker.position.lng();
      //that.getAddress(lat,lng);

      if (km_h === 0) {
        km_h = 200;
      }
      var step = (km_h * 1000 * delay) / 3600000; // in meters
      var dest = new google.maps.LatLng(coords[target][0], coords[target][1]);
      //  //console.log(coords[target][2])
      var r = coords[target][2];
      outerThis.speeed2 = r;
      outerThis.ext_voltage = "22v";

      outerThis.historyDate = coords[target][4];
      outerThis.ext_voltage = coords[target][5];
      // //console.log("outerThis.historyDate",coords);

      var distance = google.maps.geometry.spherical.computeDistanceBetween(
        dest,
        marker.position
      ); // in meters

      var numStep = distance / step;

      var i = 0;
      var deltaLat = (coords[target][0] - lat) / numStep;
      var deltaLng = (coords[target][1] - lng) / numStep;
      // //console.log('cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc',target);
      that.moveMarker = function () {
        // //console.log("Move Marker Function");
        // //console.log('zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz',a,target);
        // ye wala movemarker function h
        outerThis.sliderValue = a;
        outerThis.cummulative_Distance = coords[target][3];
        lat += deltaLat;
        lng += deltaLng;
        i += step;
        // //console.log('icons[iconselected].rotation',icons[iconselected].rotation);
        let markerDOM: any;
        var status = "RUNNING";

        if (i < distance) {
          // let iconType = 'car';
          // //console.log('iconsiconsiconsiconsiconsicons',icons);
          // //console.log(icons['iconType'].url);
          // //console.log(icons[iconType]);
          // //console.log(icons[iconType].url);
          var msg;

          var head = google.maps.geometry.spherical.computeHeading(
            marker.getPosition(),
            new google.maps.LatLng(lat, lng)
          );

          if (markerDOM) {
            markerDOM.style.transform = "rotate(" + head + "deg)";
          }
          // }

          // //console.log("Abinash");
          that.start = setTimeout(that.moveMarker, delay);
        } else {
          var head = google.maps.geometry.spherical.computeHeading(
            marker.getPosition(),
            dest
          );

          // //console.log('target',target);
          target++;
          if (target == coords.length) {
            target = 0;
          }
          that.start = setTimeout(that.goToPoint, delay);
        }
      };
      a++;

      that.rangeDetector = false;
      // //console.log("outside moveMarker function");
      if (a > coords.length) {
        // //console.log("Cord.length if condition");
        outerThis.speeed2 = 0;
      } else {
        // //console.log("Cord.length else condition");
        //that.moveMarker();
        km_h = outerThis.speed;
      }
    };
    var a = 0;

    // //console.log("Gotopoint function");
    that.goToPoint();
  }

  rangeDetector: boolean = false;
  changeRange() {
    clearTimeout(this.start);
    this.rangeDetector = true;
    var rangeVal = document.getElementById("slider1");

    this.indexValue = rangeVal["value"];

    if (this.tempMapHistory[0]["flag"] == "stop") {
      this.marker4.setPosition({
        lat: this.latLngLine[this.indexValue].lat,
        lng: this.latLngLine[this.indexValue].lng,
      });
      this.historyMap.setCenter({
        lat: this.latLngLine[this.indexValue].lat,
        lng: this.latLngLine[this.indexValue].lng,
      });
      // clearTimeout(this.start);
      // this.moveMarker();
      this.goToPoint();
    }
    if (this.tempMapHistory[0]["flag"] == "start") {
      // this.speed = 0 ;
      this.marker4.setPosition({
        lat: this.latLngLine[this.indexValue].lat,
        lng: this.latLngLine[this.indexValue].lng,
      });
      this.historyMap.setCenter({
        lat: this.latLngLine[this.indexValue].lat,
        lng: this.latLngLine[this.indexValue].lng,
      });
      this.tempMapHistory[0]["flag"] = "stop";
      // clearTimeout(this.start);
      this.goToPoint();
    }
  }

  zoomSet() {
    this.historyMap.setZoom(15);
  }

  // }

  pause() {
    this.PlayData = !this.PlayData;
    this.pauseDate = !this.pauseDate;
  }

  histortyRply(dev, data) {}
  path: any;
  devicon: any;
  latLngLine = [];

  dataArrayCoords = [];
  dataspeed = [];
  mydealer() {
    window.localStorage["token"] = window.localStorage["Dealer_token"];
    localStorage.removeItem("devices");
    window.localStorage["DataUpdate"] = "True";
    if ((window.localStorage["DataLoaded"] = "True")) {
      window.localStorage["Custumer"] = "OFF";
      this.router.navigateByUrl("add");
      // this.router.navigateByUrl("const?_status="+"OK");
    }
  }

  showStatus: boolean = false;
  flag: any;
  playing: boolean = false;
  play(playindex) {
    // //console.log('playindex',playindex);

    this.showStatus = true;

    var icontype = this.dev_id.iconType;
    var tempObj = { icontype: icontype };
    var tempDataCoordArr = this.tempMapHistory[playindex].dataArrayCoords;

    tempObj["tempDataCoordArr"] = tempDataCoordArr;

    if (this.tempMapHistory[playindex]["flag"] == "init") {
      this.animateMarker_history(this.marker4, tempDataCoordArr, 50, icontype);
      tempObj["marker"] = this.marker4;
      this.tempMapHistory[playindex]["flag"] = "stop";
      tempObj["flag"] = this.tempMapHistory[playindex]["flag"];
    } else if (this.tempMapHistory[playindex]["flag"] == "start") {
      // this.moveMarker(); // hide by me
      // clearTimeout(this.start);
      this.tempMapHistory[playindex]["flag"] = "stop";
      tempObj["flag"] = this.tempMapHistory[playindex]["flag"];
    } else if (this.tempMapHistory[playindex]["flag"] == "stop") {
      this.speed = 0;
      clearTimeout(this.start);
      this.tempMapHistory[playindex]["flag"] = "start";
      tempObj["flag"] = this.tempMapHistory[playindex]["flag"];
    }

    if (this.flag == "reset") {
      this.marker4.setPosition({
        lat: this.latLngLine[0].lat,
        lng: this.latLngLine[0].lng,
      });
      this.flag = "init";
    }
  }

  headingName = "Live Tracking";
  playingHistory: boolean = false;
  parkingPOINTS = [];
  fromTIME;
  stop_locationss = [];
  counter;

  maphistory(data) {
    let dbThis = this;
    this._openMapComponet.uniqueIdForHistory =
      "History_" + new Date().getTime();
    this._openMapComponet.pause();
    this._openMapComponet.removeDataBefore();
    this.showArea();
    this.pdfFunction(this.deviceSelect[0]);
    //this.getTravelPathReport(this.deviceSelect[0]);
    if (this.digitalInput == 1) {
      this.workingHoursFunction1(this.deviceSelect[0]);
    } else {
      this.workingHoursFunction2(this.deviceSelect[0]);
    }
    this.historyAdress = "";
    this.sliderValue = 0;
    this.showSocketData = false;
    this.Load = true;
    this.map2load = false;
    this.SpeedMeter2 = false;
    this.PlayData = true;
    this.playingHistory = false;
    let map;
    let markerCurrent;
    let markerSrc;
    var isMapInit = false;
    let markersPast;
    this.online = false;
    // this.PlayData = true;
    this.historyData = false;
    this.latLngLine = [];
    this.dataArrayCoords = [];
    var position;
    let outerThis = this;
    this.offline = true;
    from1 = null;
    this.latLongArr = [];
    this.latLongArr3 = [];
    to1 = null;

    this.dev_id = this.deviceSelect[0];
    console.log("Trssss", this.deviceSelect[0]);

    var currtime = new Date();
    var from1 = new Date(this.datefrom).toISOString();
    var to1 = new Date(this.date2).toISOString();

    var fromtime = new Date(from1).toISOString();
    var totime = new Date(to1).toISOString();

    this.fromTIME = new Date(from1).toISOString();
    //  //console.log(fromtime)

    var diff = moment(totime).diff(fromtime, "days");
    console.log("difference :" + diff);

    if (fromtime > totime || diff >= 31) {
      this.Load = false;
      let error =
        fromtime > totime
          ? "Error: From Time Never Greater then To Time"
          : "History is unavailable for more than one month";
      // let message = "Error: From Time Never Greater then To Time";
      let action;
      this.snackBar.open(error, action, {
        duration: 4000,
      });
    } else if (
      this.dev_id === null ||
      this.dev_id === undefined ||
      this.dev_id === ""
    ) {
      this.Load = false;
      let message = "Error: Please choose a device";
      let action;
      this.snackBar.open(message, action, {
        duration: 4000,
      });
    } else {
      // this.ddid = dev.did;
      // this.devicon = dev.iconType;
      console.log(this.navId);

      if (this.navId === "locationHistory") {
        this.ddid = this.dev_id.did;
      } else {
        this.ddid = this.dev_id.Device_ID;
      }

      // this.ddid = (this.navId === 'locationHistory')? this.dev_id.did : this.dev_id.Device_ID;
      console.log("DID", this.ddid, this.dev_id.did);

      this.devicon = this.dev_id.iconType;
      this.speedArr = [];
      var counter = 0;
      var countTime = setInterval(() => {
        counter++;
      }, 1000);

      if (data == 1) {
        var ft = new Date(fromtime);
        var tt = new Date(totime);
        var dname = this.deviceSelect[0];

        if (this.coloumnClicked === false) {
          var tempData = {
            fromTime: ft.toLocaleString(),
            toTime: tt.toLocaleString(),
            device_name: this.deviceName,
            device_obj: this.deviceSelect[0],
            lineThickness: this.thicknessVal,
            idleColor: this.idleColor,
            parkingColor: this.parkingColor,
            dataColor: this.dataColor,
            flag: "init",
          };
        }

        this.showTable = true;
        this.flag = "init";
        //initialize();

        this.Load = false;

        let cluster_arr = [];
        console.log(flightPath.getPath());

        this.path = flightPath.getPath();

        var cumulativeDistance = 0;
        let cumDistance = 0;
        for (let i = this.latlongObjArr.length - 1; i > 0; i--) {
          var d_name =
            this.navId === "locationHistory"
              ? this.dev_id.viewValue
              : this.dev_id.Device_Name;
          this.latlongObjArr[i].dName = d_name;
          this.speed = this.latlongObjArr[i].speed + "Km/hr";
          this.im = this.latlongObjArr[i].imei;

          this.speedArr.push(this.latlongObjArr[i].speed);

          var heading = this.latlongObjArr[i].heading;
          // this.time = gmtDateTime.local().format('h:mm:ss A');
          this.datee = JSON.stringify(this.latlongObjArr[i].insertionTime);
          // //console.log(JSON.parse(this.datee));
          // var insTime = new Date(this.datee);
          this.datee = moment(JSON.parse(this.datee)).format(
            "MMMM Do YYYY, h:mm:ss a"
          );

          var harshAcc = this.latlongObjArr[i].harshAccel;
          var harshBreak = this.latlongObjArr[i].harshBrake;
          var harshCorner = this.latlongObjArr[i].harshCorner;
          // //console.log(harshAcc,harshBreak,harshCorner);
          var fill_color = "#00F";
          var stroke_color = "#00A";
          var content = "";
          // <button value=${i} id="deletePoint" style="background-color: red;border: double;border-radius: 21%;color: white;padding: 8px 15px;cursor: pointer;opacity: 0.9;margin-left:50%">Delete</button>
          content =
            `<div id="content"><div id="bodyContent"><div><br><b>DEVICE NAME : ` +
            d_name +
            `</b><br><b>IMEI : ` +
            this.im +
            `</b><br><b>DEVICE DATE : ` +
            this.datee +
            `</b><br><b>SPEED : ` +
            this.speed +
            `</b><br><b style="margin-bottom:10px" id="addressBinding">Address : ` +
            this.contentAdd +
            `</b></div></b></div>
              </div></div>`;
          var harsh = this.latlongObjArr[i].gforce
            ? parseFloat(this.latlongObjArr[i].gforce) / 10
            : 0;
          if (harshAcc != undefined && harshAcc == "true") {
            fill_color = "#008000";
            stroke_color = "#008000";

            if (harsh != undefined && harsh != null) {
              var harshStat = outerThis.harshImpact(harsh);
              content =
                '<div id="content"><div id="bodyContent"><div><br><p style="text-align: center;font-size: initial;font-weight: 500; margin-bottom: 0px;color: #008000;">Harsh Acceleration</p><br><b>Impact : ' +
                harshStat +
                "</b><br><b>DEVICE NAME : " +
                d_name +
                "</b><br><b>IMEI : " +
                this.im +
                "</b><br><b>DEVICE DATE : " +
                this.datee +
                "</b><br><b>SPEED : " +
                this.speed +
                "</b></div>";
              ("</div></div>");
            }
          }
          if (harshBreak != undefined && harshBreak == "true") {
            fill_color = "#FF0000";
            stroke_color = "#FF0000";
            if (harsh != undefined && harsh != null) {
              var harshStat = outerThis.harshImpact(harsh);
              content =
                '<div id="content"><div id="bodyContent"><div><br><p style="text-align: center;font-size: initial;font-weight: 500; margin-bottom: 0px;color: #FF0000;">Harsh Break</p><br><b>Impact : ' +
                harshStat +
                "</b><br><b>DEVICE NAME : " +
                d_name +
                "</b><br><b>IMEI : " +
                this.im +
                "</b><br><b>DEVICE DATE : " +
                this.datee +
                "</b><br><b>SPEED : " +
                this.speed +
                "</b></div>";
              ("</div></div>");
            }
          }
          if (harshCorner != undefined && harshCorner == "true") {
            fill_color = "#c407b1";
            stroke_color = "#c407b1";
            if (harsh != undefined && harsh != null) {
              var harshStat = outerThis.harshImpact(harsh);
              content =
                '<div id="content"><div id="bodyContent"><div><br><p style="text-align: center;font-size: initial;font-weight: 500; margin-bottom: 0px;color: #c407b1;">Harsh Corner</p><br><b>Impact : ' +
                harshStat +
                "</b><br><b>DEVICE NAME : " +
                d_name +
                "</b><br><b>IMEI : " +
                this.im +
                "</b><br><b>DEVICE DATE : " +
                this.datee +
                "</b><br><b>SPEED : " +
                this.speed +
                "</b></div>";
              ("</div></div>");
            }
          }

          if (this.latlongObjArr[i].isPastData != true) {
            if (i === 0) {
              cumulativeDistance += 0;
            } else {
              cumulativeDistance += this.latlongObjArr[i].distanceFromPrevious
                ? parseFloat(this.latlongObjArr[i].distanceFromPrevious)
                : 0;
            }
            this.latlongObjArr[i]["cummulative_distance"] =
              cumulativeDistance.toFixed(2);
          } else {
            this.latlongObjArr[i]["cummulative_distance"] =
              cumulativeDistance.toFixed(2);
          }

          cumDistance =
            (this.latlongObjArr[i].cummulative_distance
              ? parseFloat(this.latlongObjArr[i].cummulative_distance)
              : 0) + cumDistance;

          var arr = [];
          arr.push(this.latlongObjArr[i].lat);
          arr.push(this.latlongObjArr[i].lng);
          arr.push(this.latlongObjArr[i].speed);
          arr.push(cumDistance);
          arr.push(this.datee);
          arr.push(this.latlongObjArr[i].external_Battery);
          arr.push(this.latlongObjArr[i].heading);
          let cord = {
            lat: this.latlongObjArr[i].lat,
            lng: this.latlongObjArr[i].lng,
          };
          this.dataArrayCoords.push(arr);

          this.latLngLine.push(cord);
          var contentString =
            "<div>" +
            "<div>" +
            '<p style="margin-bottom: 5px;font-weight:700">' +
            this.deviceName +
            "</p>" +
            "</div>";
          var iconSrc = this.iconSelector("RUNNING", "truck", {});
          // 'https://chart.googleapis.com/chart?chst=d_map_pin_letter&chld=S|00FF00|000000'
          // this.iconSelector("RUNNING","car",{});

          var iconDest =
            "https://chart.googleapis.com/chart?chst=d_map_pin_letter&chld=D|FF0000|000000";

          // =====================================added==============================

          if (
            this.latlongObjArr[i].interpolated == null ||
            this.latlongObjArr[i].interpolated == undefined ||
            this.latlongObjArr[i].interpolated.length == 0
          ) {
            this.lat = this.latlongObjArr[i].lat;
            this.lng = this.latlongObjArr[i].lng;
            this.path.push(new google.maps.LatLng(this.lat, this.lng));

            if (this.dataColor === true) {
              var markersPasts = new google.maps.Marker({
                position: new google.maps.LatLng(this.lat, this.lng),
                icon: {
                  path: google.maps.SymbolPath.CIRCLE,
                  fillColor: fill_color,
                  fillOpacity: 0.6,
                  strokeColor: stroke_color,
                  strokeOpacity: 0.9,
                  strokeWeight: 5,
                  scale: 2,
                },
                map: map,
              });

              markersPasts["infowindow"] = new google.maps.InfoWindow({
                content: content,
              });

              google.maps.event.addListener(markersPasts, "click", function () {
                var lattitude = markersPasts.position.lat();
                var longitude = markersPasts.position.lng();
                var latlng_1 = {
                  lat: lattitude,
                  long: longitude,
                };
                outerThis.contactService
                  .getAddressByApi(latlng_1)
                  .subscribe((res) => {
                    if (res.message == "Address not found in databse") {
                      var geocoder = new google.maps.Geocoder();
                      var latlng = new google.maps.LatLng(lattitude, longitude);

                      var request = {
                        latLng: latlng,
                      };
                      // //console.log('latlongVal', request)
                      var innerThis = this;
                      this["infowindow"].open(map, innerThis);
                      geocoder.geocode(request, function (data, status) {
                        if (status == google.maps.GeocoderStatus.OK) {
                          if (data[0] != null) {
                            // innerThis.contentAdd = data[0].formatted_address;
                            var tempAdd = data[0].formatted_address;
                            var getAddressContent =
                              document.getElementById("addressBinding");
                            getAddressContent.innerHTML = "Address :" + tempAdd;
                          } else {
                            // //console.log("No address available")
                            var tempAdd_1 = "No address available";
                            var getAddressContent =
                              document.getElementById("addressBinding");
                            getAddressContent.innerHTML =
                              "Address :" + tempAdd_1;
                          }
                        } else {
                          var tempAdd_2 = "NA";
                          var getAddressContent =
                            document.getElementById("addressBinding");
                          getAddressContent.innerHTML = "Address :" + tempAdd_2;
                          //console.log('aaaaaaaaaaaaaa',getAddressContent);
                        }
                      });
                    } else {
                      var innerThis_1 = this;

                      this["infowindow"].open(map, innerThis_1);
                      var tempAdd = res.address;
                      //console.log('innerThis_1.contentAdd',tempAdd);
                      var chkTmout = setTimeout(function () {
                        var getAddressContent =
                          document.getElementById("addressBinding");
                        // //console.log('getAddressContent',getAddressContent);
                        getAddressContent.innerHTML = "Address :" + tempAdd;
                        clearTimeout(chkTmout);
                      }, 500);
                    }
                  });
              });
              // cluster_arr.push(markersPast);
            }

            if (i == 1) {
              markerCurrent = new google.maps.Marker({
                position: new google.maps.LatLng(this.lat, this.lng),
                map: map,
                icon: iconDest,
              });
              // outerThis.marker4  = markerCurrent;
              map.setCenter(new google.maps.LatLng(this.lat, this.lng));
              flightPath.setMap(map);
              zoomToObject(flightPath);
            }
            if (i == this.latlongObjArr.length - 1) {
              markerSrc = new google.maps.Marker({
                position: new google.maps.LatLng(this.lat, this.lng),
                map: map,
                icon: iconSrc,
                scaledSize: new google.maps.Size(20, 20),
              });
              //  markerSrc['infowindow'] = new google.maps.InfoWindow({ content: content });
              const infowindow = new google.maps.InfoWindow({
                content: contentString,
              });
              infowindow.open(map, markerSrc);
              markerSrc.addListener("click", () => {
                infowindow.open(map, markerSrc);
              });
              outerThis.marker4 = markerSrc;
            }
          } else {
            for (
              let k = 0;
              k < this.latlongObjArr[i].interpolated.length;
              k++
            ) {
              if (
                this.latlongObjArr[i].interpolated[k].location.latitude ==
                  null ||
                this.latlongObjArr[i].interpolated[k].location.longitude == null
              ) {
                this.lat = this.latlongObjArr[i].lat;
                this.lng = this.latlongObjArr[i].lng;
              } else {
                this.lat =
                  this.latlongObjArr[i].interpolated[k].location.latitude;
                this.lng =
                  this.latlongObjArr[i].interpolated[k].location.longitude;
              }

              this.path.push(new google.maps.LatLng(this.lat, this.lng));

              if (this.dataColor) {
              }
            }
          }
        }

        //console.log(this.coloumnClicked) ;
        if (this.coloumnClicked === false) {
          //tempData['dataArrayCoords'] = this.dataArrayCoords;
          tempData["dataArrayCoords"] = this.latlongObjArr;
        }

        // //console.log('this.dataArrayCoords',this.dataArrayCoords);
        if (this.dataArrayCoords.length < 1) {
          var fdd = new Date(this.datefrom);
          var tdd = new Date(this.date2);
          swal(
            "No Data Found",
            "Vehicle has not moved from" +
              " " +
              moment(fdd).format("LLL") +
              "to " +
              moment(tdd).format("LLL")
          ).then(
            (ans) => {
              //console.log(ans);
            },
            (err) => {
              //console.log(err);
            }
          );
        }

        this.seekBarValue = this.dataArrayCoords.length;

        this.maxSpeedd = Math.max.apply(null, this.speedArr);
        this.dis = true;
        console.info("getDistance 1");
        this.contactService
          .getDistance(
            this.ddid,
            totime,
            fromtime,

            this.satelliteDisabled ? this.satelite : undefined
          )
          .subscribe((data3) => {
            this.data2 = data3;

            // initialize();
            //  //console.log(this.data2);
            let a = this.data2["Distance"] ? this.data2["Distance"] : 0;
            if (this.coloumnClicked === false) {
              tempData["mileage"] = a;
              this.tempMapHistory.push(tempData);
            }

            this.total_dis = a;
            let b = this.data2["Average Speed"]
              ? this.data2["Average Speed"]
              : 0;
            this.avg_speed = b;

            this.ideal_time = this.data2["Idle Time"]
              ? this.minToHoursConversion(this.data2["Idle Time"])
              : 0;
            if (parseFloat(this.ideal_time) < 0) {
              this.ideal_time = 0;
            }

            this.historyDataCondition = true;

            var playerSeekbar: any;
          });
      } else {
        this.contactService
          .getCurrentLocation1(
            this.ddid,
            fromtime,
            totime,
            this.satelliteDisabled ? this.satelite : undefined
          )
          .subscribe((data3: any) => {
            if (data3) {
              clearInterval(countTime);
            }
            let latLongArray: any[] = [];
            data3.forEach((deData) => {
              latLongArray.push({
                long: deData.lng,
                lat: deData.lat,
              });
            });

            outerThis.contactService
              .getAddressByApiBulk(latLongArray)
              .subscribe((latLongAddress) => {
                if (latLongAddress && latLongAddress.length) {
                  data3.forEach((deData, index) => {
                    outerThis.contactService.latLongAddress[
                      deData.lng + "_" + deData.lat
                    ] = latLongAddress[index];
                  });
                }
                var ft = new Date(fromtime);
                var tt = new Date(totime);
                var dname = this.deviceSelect[0];

                if (this.coloumnClicked === false) {
                  var tempData = {
                    fromTime: ft.toLocaleString(),
                    toTime: tt.toLocaleString(),
                    device_name: this.deviceName,
                    device_obj: this.deviceSelect[0],
                    lineThickness: this.thicknessVal,
                    idleColor: this.idleColor,
                    parkingColor: this.parkingColor,
                    dataColor: this.dataColor,
                    flag: "init",
                  };
                }

                this.showTable = true;

                dbThis.latlongObjArr = data3;
                this.flag = "init";
                //initialize();
                this.Load = false;
                let cluster_arr = [];
                this.path = flightPath.getPath();
                var cumulativeDistance = 0;
                let cumDistance = 0;
                for (let i = dbThis.latlongObjArr.length - 1; i > 0; i--) {
                  var d_name =
                    this.navId === "locationHistory"
                      ? this.dev_id.viewValue
                      : this.dev_id.Device_Name;
                  dbThis.latlongObjArr[i].dName = d_name;
                  this.speed = dbThis.latlongObjArr[i].speed + "Km/hr";
                  this.im = dbThis.latlongObjArr[i].imei;

                  this.speedArr.push(dbThis.latlongObjArr[i].speed);

                  var heading = dbThis.latlongObjArr[i].heading;

                  this.datee = JSON.stringify(
                    dbThis.latlongObjArr[i].insertionTime
                  );

                  this.datee = moment(JSON.parse(this.datee)).format(
                    "MMMM Do YYYY, h:mm:ss a"
                  );
                  var harshAcc = dbThis.latlongObjArr[i].harshAccel;
                  var harshBreak = dbThis.latlongObjArr[i].harshBrake;
                  var harshCorner = dbThis.latlongObjArr[i].harshCorner;

                  var fill_color = "#00F";
                  var stroke_color = "#00A";
                  var content = "";

                  content =
                    `<div id="content"><div id="bodyContent"><div><br><b>DEVICE NAME : ` +
                    d_name +
                    `</b><br><b>IMEI : ` +
                    this.im +
                    `</b><br><b>DEVICE DATE : ` +
                    this.datee +
                    `</b><br><b>SPEED : ` +
                    this.speed +
                    `</b><br><b style="margin-bottom:10px" id="addressBinding">Address : ` +
                    this.contentAdd +
                    `</b></div></b></div>
              </div></div>`;

                  var harsh = dbThis.latlongObjArr[i].gforce
                    ? parseFloat(dbThis.latlongObjArr[i].gforce) / 10
                    : 0;
                  if (harshAcc != undefined && harshAcc == "true") {
                    fill_color = "#008000";
                    stroke_color = "#008000";

                    if (harsh != undefined && harsh != null) {
                      var harshStat = outerThis.harshImpact(harsh);
                      content =
                        '<div id="content"><div id="bodyContent"><div><br><p style="text-align: center;font-size: initial;font-weight: 500; margin-bottom: 0px;color: #008000;">Harsh Acceleration</p><br><b>Impact : ' +
                        harshStat +
                        "</b><br><b>DEVICE NAME : " +
                        d_name +
                        "</b><br><b>IMEI : " +
                        this.im +
                        "</b><br><b>DEVICE DATE : " +
                        this.datee +
                        "</b><br><b>SPEED : " +
                        this.speed +
                        "</b></div>";
                      ("</div></div>");
                    }
                  }
                  if (harshBreak != undefined && harshBreak == "true") {
                    fill_color = "#FF0000";
                    stroke_color = "#FF0000";
                    if (harsh != undefined && harsh != null) {
                      var harshStat = outerThis.harshImpact(harsh);
                      content =
                        '<div id="content"><div id="bodyContent"><div><br><p style="text-align: center;font-size: initial;font-weight: 500; margin-bottom: 0px;color: #FF0000;">Harsh Break</p><br><b>Impact : ' +
                        harshStat +
                        "</b><br><b>DEVICE NAME : " +
                        d_name +
                        "</b><br><b>IMEI : " +
                        this.im +
                        "</b><br><b>DEVICE DATE : " +
                        this.datee +
                        "</b><br><b>SPEED : " +
                        this.speed +
                        "</b></div>";
                      ("</div></div>");
                    }
                  }
                  if (harshCorner != undefined && harshCorner == "true") {
                    fill_color = "#c407b1";
                    stroke_color = "#c407b1";
                    if (harsh != undefined && harsh != null) {
                      var harshStat = outerThis.harshImpact(harsh);
                      content =
                        '<div id="content"><div id="bodyContent"><div><br><p style="text-align: center;font-size: initial;font-weight: 500; margin-bottom: 0px;color: #c407b1;">Harsh Corner</p><br><b>Impact : ' +
                        harshStat +
                        "</b><br><b>DEVICE NAME : " +
                        d_name +
                        "</b><br><b>IMEI : " +
                        this.im +
                        "</b><br><b>DEVICE DATE : " +
                        this.datee +
                        "</b><br><b>SPEED : " +
                        this.speed +
                        "</b></div>";
                      ("</div></div>");
                    }
                  }

                  if (dbThis.latlongObjArr[i].isPastData != true) {
                    if (i === 0) {
                      cumulativeDistance += 0;
                    } else {
                      cumulativeDistance += dbThis.latlongObjArr[i]
                        .distanceFromPrevious
                        ? parseFloat(
                            dbThis.latlongObjArr[i].distanceFromPrevious
                          )
                        : 0;
                    }
                    dbThis.latlongObjArr[i]["cummulative_distance"] =
                      cumulativeDistance.toFixed(2);
                  } else {
                    dbThis.latlongObjArr[i]["cummulative_distance"] =
                      cumulativeDistance.toFixed(2);
                  }

                  var arr = [];
                  cumDistance =
                    (dbThis.latlongObjArr[i].cummulative_distance
                      ? parseFloat(dbThis.latlongObjArr[i].cummulative_distance)
                      : 0) + cumDistance;
                  arr.push(dbThis.latlongObjArr[i].lat);
                  arr.push(dbThis.latlongObjArr[i].lng);
                  arr.push(dbThis.latlongObjArr[i].speed);
                  arr.push(cumDistance);
                  arr.push(this.datee);
                  arr.push(dbThis.latlongObjArr[i].external_Battery);
                  arr.push(dbThis.latlongObjArr[i].heading);
                  let cord = [
                    dbThis.latlongObjArr[i].lng,
                    dbThis.latlongObjArr[i].lat,
                  ];
                  this.dataArrayCoords.push(arr);

                  this.latLngLine.push(cord);
                  var contentString =
                    "<div>" +
                    "<div>" +
                    '<p style="margin-bottom: 5px;font-weight:700">' +
                    this.deviceName +
                    "</p>" +
                    "</div>";
                  var iconSrc = this.iconSelector("RUNNING", "truck", {});
                  // 'https://chart.googleapis.com/chart?chst=d_map_pin_letter&chld=S|00FF00|000000'
                  // this.iconSelector("RUNNING","car",{});

                  var iconDest =
                    "https://chart.googleapis.com/chart?chst=d_map_pin_letter&chld=D|FF0000|000000";

                  if (
                    dbThis.latlongObjArr[i].interpolated == null ||
                    dbThis.latlongObjArr[i].interpolated == undefined ||
                    dbThis.latlongObjArr[i].interpolated.length == 0
                  ) {
                    this.lat = dbThis.latlongObjArr[i].lat;
                    this.lng = dbThis.latlongObjArr[i].lng;
                    this.path.push(new google.maps.LatLng(this.lat, this.lng));

                    if (this.dataColor === true) {
                    }
                  } else {
                    for (
                      let k = 0;
                      k < dbThis.latlongObjArr[i].interpolated.length;
                      k++
                    ) {
                      if (
                        dbThis.latlongObjArr[i].interpolated[k].location
                          .latitude == null ||
                        dbThis.latlongObjArr[i].interpolated[k].location
                          .longitude == null
                      ) {
                        this.lat = dbThis.latlongObjArr[i].lat;
                        this.lng = dbThis.latlongObjArr[i].lng;
                      } else {
                        this.lat =
                          dbThis.latlongObjArr[i].interpolated[
                            k
                          ].location.latitude;
                        this.lng =
                          dbThis.latlongObjArr[i].interpolated[
                            k
                          ].location.longitude;
                      }
                      this.path.push(
                        new google.maps.LatLng(this.lat, this.lng)
                      );
                    }
                  }
                }

                if (this.coloumnClicked === false) {
                  tempData["dataArrayCoords"] = dbThis.latlongObjArr;
                }

                if (this.dataArrayCoords.length < 1) {
                  var fdd = new Date(this.datefrom);
                  var tdd = new Date(this.date2);
                  swal(
                    "No Data Found",
                    "Vehicle has not moved from" +
                      " " +
                      moment(fdd).format("LLL") +
                      "to " +
                      moment(tdd).format("LLL")
                  ).then(
                    (ans) => {
                      //console.log(ans);
                    },
                    (err) => {
                      //console.log(err);
                    }
                  );
                }

                this.seekBarValue = this.dataArrayCoords.length;

                this.maxSpeedd = Math.max.apply(null, this.speedArr);
                this.dis = true;
                console.info("getDistance 2");
                this.contactService
                  .getDistance(
                    this.ddid,
                    totime,
                    fromtime,

                    this.satelliteDisabled ? this.satelite : undefined
                  )
                  .subscribe((data3) => {
                    this.data2 = data3;

                    let db_data = _.chain(dbThis.latlongObjArr)
                      .find({ imei: dbThis.ddid })
                      .value();

                    if (db_data != undefined) {
                      // initialize();
                      let a = db_data.cummulative;
                      // if(this.distanceVariation){
                      //   if(this.distanceVariation[0]=="+"){
                      //     var milege=(a/100)*(Number(this.distanceVariation.substring(1)))
                      // console.log("MILEGE->",milege,'-',a);
                      //     a=a+milege

                      //   }else{
                      //     var milege=(a/100)*(Number(this.distanceVariation.substring(1)))
                      // console.log("MILEGE->",milege,'-',a);
                      //     a=a-milege
                      //   }
                      // }
                      if (this.coloumnClicked === false) {
                        tempData["mileage"] = a.toFixed(2);

                        tempData["aIndex"] = this.tempMapHistory.length;
                        this.tempMapHistory.push(tempData);
                      }

                      this.total_dis = a;

                      this.avg_speed = db_data.speed;

                      this.ideal_time = this.data2["Idle Time"]
                        ? this.minToHoursConversion(this.data2["Idle Time"])
                        : 0;
                      if (parseFloat(this.ideal_time) < 0) {
                        this.ideal_time = 0;
                      }

                      this.historyDataCondition = true;

                      var playerSeekbar: any;
                      $(document).ready(function () {
                        playerSeekbar = document.getElementById("slider1");

                        playerSeekbar != null &&
                          (playerSeekbar.oninput = function () {
                            zoomToObject(flightPath);
                            outerThis.changeRange();
                          });
                      });
                    }
                  });
              });
          });
      }
      let min_time = this.minIdleTime;
      var deviceObjectid =
        this.navId === "locationHistory" ? this.dev_id.id : this.dev_id._id;
      if (this.idleColor === true) {
        this.idlePlot(fromtime, totime, deviceObjectid, min_time, map);
      }
      var stop_locations = [];
      if (this.parkingColor === true) {
        var userid =
          this.dev_id.user._id != undefined
            ? this.dev_id.user._id
            : this.dev_id.user;
        this.contactService
          .stoppage_points(deviceObjectid, fromtime, totime, userid)
          .subscribe((res) => {
            let test = res;
            // let test = res;
            this.Load = false;
            this.stoppageCount = test.length != 0 ? test.length : 0;
            for (var i = 0; i < test.length; i++) {
              this.stoppage_container = [];
              this.stoppage_container.push(test[i].lat);
              this.stoppage_container.push(test[i].long);

              this.arrival = new Date(test[i].arrival_time);
              this.stoppage_container.push(this.arrival);
              this.departure = new Date(test[i].departure_time);
              this.stoppage_container.push(this.departure);
              stop_locations.push(this.stoppage_container);
              this.stop_locationss.push(this.stoppage_container);
            }
            // debugger;
            console.log("initParking", stop_locations.length);
            if (stop_locations.length > 0) {
              // for(var l=0;l<stop_locations.length;l++){
              //   this.parkingPOINTS.push(this.parkingPonit(fromtime,stop_locations,l))
              //   console.log("KSSSSSSSSS",this.parkingPOINTS)
              // }

              console.log("initParking");
            } else {
              console.log("In Else part initParking", stop_locations);
            }
            this._openMapComponet.setStoppagePoints(
              this._openMapComponet.uniqueIdForHistory,
              this.stop_locationss
            );
          });
      }
    }
    // //console.log(totime)
    this.latLongArr2 = [];
    var customTxt;
    var txt;
    function geocodePosition(pos, callback) {
      var geocoder = new google.maps.Geocoder();
      geocoder.geocode(
        {
          latLng: pos,
        },
        function (responses) {
          callback(responses[0].formatted_address);
        }
      );
    }
    var k;

    function initParking() {
      console.log("counter + 5000", counter + 8000);
      var ttVal = counter + 5000;
      var callTimeout = setTimeout(() => {
        isMapInit = true;
        // ============================
        // var pinImage = new google.maps.MarkerImage("https://png.icons8.com/office/30/000000/parking.png");
        var pinImage = new google.maps.MarkerImage(
          "../../assets/image/parkingPoint1.png"
        );
        var infowindow = new google.maps.InfoWindow();

        // var marker: any;
        var k: any;
        var l: number;

        console.log("stoppagelocationArr", stop_locations.length);
        for (l = 0; l < stop_locations.length; l++) {
          outerThis.latitude = stop_locations[l][0];
          outerThis.longitude = stop_locations[l][1];
          outerThis.arrivalTime = new Date(
            stop_locations[l][2]
          ).toLocaleString();
          outerThis.departureTime = new Date(
            stop_locations[l][3]
          ).toLocaleString();
          outerThis.addresslocation = stop_locations[l][4];

          var fd = new Date(outerThis.arrivalTime).getTime();
          var td = new Date(outerThis.departureTime).getTime();
          var time_difference = td - fd;
          var total_min = time_difference / 60000;
          var hours = total_min / 60;
          var rhours = Math.floor(hours);
          var minutes = (hours - rhours) * 60;
          var rminutes = Math.round(minutes);
          outerThis.Durations = rhours + ":" + rminutes;

          let marker = new google.maps.Marker({
            position: new google.maps.LatLng(
              stop_locations[l][0],
              stop_locations[l][1]
            ),
            map: outerThis.historyMap,
            icon: pinImage,
          });

          google.maps.event.addListener(marker, "dragend", function () {
            this.geocodePosition(marker.getPosition());
          });
          outerThis.historyMap.setCenter(marker.getPosition());
          // console.log(outerThis.parkingPonit(fromtime,stop_locations,l),'erueruu')
          // outerThis.counter=l

          // setTimeout(function(){
          var content =
            "<div><div> Arrival Time-: " +
            outerThis.arrivalTime +
            "</div><br><div>Departure Time-: " +
            outerThis.departureTime +
            "</div><br><div>Time Duration-: " +
            outerThis.Durations +
            " </div></br><div> Latitude-: " +
            outerThis.latitude +
            " </div></br><div> Longitude-: " +
            outerThis.longitude +
            " </div><br></div>";

          google.maps.event.addListener(
            marker,
            "click",
            (function (marker, content, infowindow) {
              return function () {
                geocodePosition(marker.getPosition(), function (result) {
                  infowindow.setContent(content);
                  infowindow.open(map, marker, content);
                });
                // }, 2000);
              };
            })(marker, content, infowindow)
          );
        }
        clearTimeout(callTimeout);
      }, ttVal);
    }

    function initialize() {
      const myOptions = {
        zoom: 2,
        center: new google.maps.LatLng(18.602941, 73.777147),
        mapTypeId: google.maps.MapTypeId.ROADMAP,
      };
      console.log("manoj 7");
      map = new google.maps.Map(document.getElementById("map2"), myOptions);
      console.log("mapmapmapmapmapmapmapmapmapmapmapmapmapmap", map);
      outerThis.historyMap = map;
      var trafficLayer = new google.maps.TrafficLayer();
      trafficLayer.setMap(map);

      isMapInit = true;

      var zoomBar: any;
      zoomBar = document.getElementById("myRange");
      map.setZoom(map.getZoom());

      zoomBar.value = map.getZoom();

      zoomBar.oninput = function () {
        //console.log('zoomValue',map.getZoom());
        map.setZoom(parseInt(this.value));
      };

      google.maps.event.addListener(map, "zoom_changed", function (event) {
        //console.log("Inside zoom in out function");
        if (zoomBar.value) zoomBar.value = map.getZoom();
      });
    }

    function toggleGeofence1(choice) {
      // //console.log(choice);
      if (choice) {
        outerThis.geoService(map);
      } else {
        outerThis.removeGeofence();
        outerThis.enableGeofenceComponent = !outerThis.enableGeofenceComponent;
      }
    }

    this.toggleGeofence1 = toggleGeofence1;
    var routePath;
    var flightPath;
    var allSourceDestinationMarkers = [];
    var poiMarkers = [];
    var allRoutePathPoints = [];

    function routeDetails1(uId, choice) {
      // //console.log(uId);

      if (choice) {
        outerThis.contactService.getRouteDetail_path(uId).subscribe((res) => {
          // //console.log("abcd2", res)
          routePath = res;
          showRoutes1();
          outerThis.enableRouteComponent = !outerThis.enableRouteComponent;
        });
      } else {
        //removing Route source destination markers
        for (var i = 0; i < allSourceDestinationMarkers.length; i++) {
          allSourceDestinationMarkers[i].setMap(null);
        }
        allSourceDestinationMarkers = [];
        //removing Route points
        for (var i = 0; i < allRoutePathPoints.length; i++) {
          allRoutePathPoints[i].setMap(null);
        }
        allRoutePathPoints = [];
        outerThis.enableRouteComponent = !outerThis.enableRouteComponent;
      }
    }

    var mapData, poiData;
    var marker1;
    this.routeDetails1 = routeDetails1;
    function showRoutes1() {
      // //console.log(routePath[1].path);
      //["skyblue","green","purple","orange","darkblue","yellow","red"]
      let colors = [
        "1E90FF",
        "28B463",
        "6C3483",
        "D35400",
        "2C3E50",
        "F1C40F",
        "E74C3C",
      ];
      for (var j = 0; j < routePath.length; j++) {
        //outerThis.dataArrayCoords = [];
        mapData = [];
        for (var i = 0; i < routePath[j].path.length; i++) {
          var arr = [];
          arr.push(routePath[j].path[i].location.coordinates[1]);
          arr.push(routePath[j].path[i].location.coordinates[0]);
          //outerThis.dataArrayCoords.push(arr);

          mapData.push({
            lat: routePath[j].path[i].location.coordinates[1],
            lng: routePath[j].path[i].location.coordinates[0],
          });
        }

        ////console.log(outerThis.dataArrayCoords);

        // //console.log(mapData[0]);
        // //console.log(mapData[mapData.length - 1]);

        var colorForPath = colors[j % colors.length];
        var strokeColor = "#" + colorForPath;
        // //console.log("j:" + j + "Color:" + strokeColor + " deno:" + (colors.length - 1) + "nume:" + (j + 1));

        var sourceIcon =
          "http://www.googlemapsmarkers.com/v1/S/" +
          "009933" +
          "/FFFFFF/000000/ "; //colorForPath
        var pinImage = new google.maps.MarkerImage(sourceIcon);
        var marker = new google.maps.Marker({
          position: mapData[0],
          map: map,
          icon: pinImage,
          title: "Source",
        });
        allSourceDestinationMarkers.push(marker);
        console.log(allSourceDestinationMarkers);

        var destinationIcon =
          "http://www.googlemapsmarkers.com/v1/D/" +
          "FF3300" +
          "/FFFFFF/000000/ "; //colorForPath
        var pinImage1 = new google.maps.MarkerImage(destinationIcon);
        marker1 = new google.maps.Marker({
          position: mapData[mapData.length - 1],
          map: map,
          icon: pinImage1,
          title: "Destination",
        });
        allSourceDestinationMarkers.push(marker1);

        flightPath = new google.maps.Polyline({
          path: mapData,
          geodesic: true,
          strokeColor: strokeColor,
          strokeOpacity: 1.0,
          strokeWeight: 6,
        });
        allRoutePathPoints.push(flightPath);
        // //console.log(mapData);
        flightPath.setMap(map);
        // //console.log(flightPath);
      }
    }

    function togglePOI1(choice) {
      // //console.log(choice);
      if (choice) {
        getPOIs1(this.useridd);
      } else {
        removePOIs1();
        outerThis.enablePOIComponent = !outerThis.enablePOIComponent;
      }
    }

    this.togglePOI1 = togglePOI1;

    var pois = [];
    function getPOIs1(uId) {
      outerThis.contactService.getPOI(uId).subscribe((res) => {
        // //console.log("pois", res)
        pois = res;
        plotAllPOIs1();
        outerThis.enablePOIComponent = !outerThis.enablePOIComponent;
      });
    }

    function removePOIs1() {
      for (var i = 0; i < poiMarkers.length; i++) {
        poiMarkers[i].setMap(null);
      }
      poiMarkers = [];
    }

    function plotAllPOIs1() {
      console.log("PLOTING POIIIISISISISI");

      for (var i = 0; i < pois.length; i++) {
        //var arr = [];
        poiData = [];
        //arr.push(pois[i].poi.location.coordinates[1]);
        //arr.push(pois[i].poi.location.coordinates[0]);

        poiData.push({
          lat: pois[i].poi.location.coordinates[1],
          lng: pois[i].poi.location.coordinates[0],
        });

        var poiIcon = "/assets/images/liveTrackIcons/building.jpg";
        // var poiIcon="https://img.icons8.com/ios-filled/50/000000/building-with-rooftop-terrace.png"
        // building.jpeg
        // var poiIcon = "https://developers.google.com/maps/documentation/javascript/examples/full/images/beachflag.png";
        //"http://www.googlemapsmarkers.com/v1/P/" + "000000" + "/FFFFFF/000000/ ";//'/assets/images/poi.png';//colorForPath
        var poiImage = new google.maps.MarkerImage(poiIcon);
        var marker = new google.maps.Marker({
          position: poiData[0],
          map: map,
          icon: poiImage,
          title: pois[i].poi.poiname,
        });
        poiMarkers.push(marker);

        var infobox_numberPlate = new InfoBox({
          content:
            "<div class='infobox' style='padding:2px;background:#575656;margin-left: -25px;'><small><b style='color: #ffffff;font-weight:300;font-size:12px;'>" +
            pois[i].poi.poiname +
            "</b></small></div>",
          disableAutoPan: false,
          maxWidth: 150,
          alignBottom: true,
          pixelOffset: new google.maps.Size(-25, -20),
          zIndex: null,
          boxStyle: {
            opacity: 1,
            zIndex: 999,
            width: "auto",
            padding: "2px",
          },
          closeBoxURL: "",
          infoBoxClearance: new google.maps.Size(1, 1),
        });

        infobox_numberPlate.open(map, marker);
      }
    }

    var lineSymbol = {
      path: "M 0,-1 0,1",
      strokeOpacity: 1,
      scale: 4,
    };

    var flightPath = new google.maps.Polyline({
      geodesic: true,
      strokeColor: "#0000FF",
      strokeOpacity: 1.0,
      strokeWeight: parseInt(this.thicknessVal),
      icons: [
        {
          icon: {
            strokeColor: "#056608",

            fillColor: "#056608",
            strokeOpacity: 0.8,
            strokeWeight: parseInt(this.thicknessVal),
            path: google.maps.SymbolPath.FORWARD_CLOSED_ARROW,
          },
          offset: "0",
          repeat: "100px",
        },
        // ,
        // {
        //   icon: {
        //     strokeColor: '#FF0000 ',
        //     fillColor: '#FF0000',
        //     strokeOpacity: 0.8,
        //     strokeWeight: parseInt(this.thicknessVal),
        //     path: google.maps.SymbolPath.BACKWARD_CLOSED_ARROW
        //   },
        //   offset: '0',
        //   repeat: '100px'
        // }
      ],
    });

    function zoomToObject(obj) {
      var bounds = new google.maps.LatLngBounds();
      var points = obj.getPath().getArray();
      for (var n = 0; n < points.length; n++) {
        bounds.extend(points[n]);
      }
      map.fitBounds(bounds);
    }

    this.parkingData(fromtime, totime, this.useridd, this.dev_id);

    this.notificationData(fromtime, totime, this.useridd, this.dev_id);
  }
  parkingPonit(fromtime, stop_locations, l) {
    console.log(fromtime, stop_locations, l, "--------------");
    console.info("getDistance 3");
    var data;
    this.contactService
      .getDistance(
        this.ddid,
        stop_locations[l][2].toISOString(),
        fromtime,

        this.satelliteDisabled ? this.satelite : undefined
      )
      .subscribe((data3: any) => {
        console.log("DADADADADADADAD--->", data3.Distance);
        data = data3;
        return data3;
      });
  }

  harshImpact(harshVal) {
    // //console.log('harshVal',harshVal)
    if (harshVal < 3.5) {
      var hStatus = "Low";
      return hStatus;
    }
    if (harshVal >= 3.5 && harshVal < 4.5) {
      var hStatus = "Medium";
      return hStatus;
    }
    if (harshVal >= 4.5 && harshVal < 5) {
      var hStatus = "High";
      return hStatus;
    }
    if (harshVal >= 5) {
      // //console.log('Severe');
      var hStatus = "SEVERE";
      return hStatus;
    }
  }

  ideal_time: any;
  total_dis: any;
  dis: Boolean = false;
  avg_speed: any;
  //Geofence
  drawPolygon(geofence) {
    this._openMapComponet.geofenceAction(
      this.enableGeofenceComponent,
      geofence._id
    );
  }
  drawOld(zzz, yyy) {
    console.log("zzz", zzz, "yyy", yyy);
    //console.log('yyy', yyy);
    var map;
    var infoWindow;

    this.cordin = [];
    let a = zzz.coordinates[0];
    for (let k = 0; k < a.length; k++) {
      let b = {
        lat: a[k][1],
        lng: a[k][0],
      };
      this.cordin.push(b);
    }

    var GeoFencCoords = this.cordin;
    var GeoName = yyy;

    initMap(GeoFencCoords);
    let outerThis = this;
    function initMap(GeoFencCoords) {
      console.log("manoj 1");
      map = new google.maps.Map(document.getElementById("map"), {
        zoom: 17,
        center: { lat: GeoFencCoords[0].lat, lng: GeoFencCoords[0].lng },
        mapTypeId: "terrain",
      });

      var bermudaTriangle = new google.maps.Polygon({
        paths: GeoFencCoords,
        strokeColor: "#FF0000",
        strokeOpacity: 0.8,
        strokeWeight: 3,
        fillColor: "#FF0000",
        fillOpacity: 0.35,
      });
      bermudaTriangle.setMap(map);

      // Add a listener for the click event.
      bermudaTriangle.addListener("click", showArrays);

      infoWindow = new google.maps.InfoWindow();
    }

    /** @this {google.maps.Polygon} */
    function showArrays(event) {
      var vertices = this.getPath();

      var contentString = "<b>Geo Fence</b><br>" + "Name: " + GeoName;

      infoWindow.setContent(contentString);
      infoWindow.setPosition(event.latLng);

      infoWindow.open(map);
    }
  }
  device_imei = [];
  private socket_Geo;
  data2: any;
  //Get Device Imei
  calldevice() {
    this.emailid = JSON.parse(
      window.atob(window.localStorage.token.split(".")[1])
    ).email;
    this.useridd = JSON.parse(
      window.atob(window.localStorage.token.split(".")[1])
    )._id;

    this.contactService
      .getDevice(this.emailid, this.useridd)
      .subscribe((data) => {
        this.devicess = data;

        for (let i = 0; i < this.devicess.devices.length; i++) {
          // if (this.devicess.devices[i].type_of_device == "Tracker") {

          let a = {
            did: this.devicess.devices[i].Device_ID,
            dname: this.devicess.devices[i].Device_Name,
          };
          this.device_imei.push(a);
        }

        // }
        this.geoFenceaction(this.device_imei);
      });
  }

  minToHoursConversion(num) {
    var hours = Math.floor(num / 3600);
    num %= 3600;
    var minutes = Math.floor(num / 60);
    var seconds = num % 60;
    //     var hours = (num / 60);
    //   var rhours = Math.floor(hours);
    //   var minutes = (hours - rhours) * 60;
    // var rminutes = Math.round(minutes);
    return hours + " hrs " + minutes + " min ";
  }

  //GeoFence Action

  geoFenceaction(imei) {
    for (let i = 0; i < imei.length; i++) {}
  }
  new: any;
  table1ch() {
    myFunction();
    function myFunction() {
      var input, filter, table, tr, td, i;
      input = document.getElementById("myInput");

      filter = input.value.toUpperCase();
      table = document.getElementById("myTable");
      tr = table.getElementsByTagName("tr");
      for (i = 0; i < tr.length; i++) {
        td = tr[i].getElementsByTagName("td")[0];
        if (td) {
          if (td.innerHTML.toUpperCase().indexOf(filter) > -1) {
            tr[i].style.display = "";
          } else {
            tr[i].style.display = "none";
          }
        }
      }
    }
  }
  share_id: any;
  share_name: any;
  vewdev(id, name, type, device) {
    // //console.log("Inside adddiv");
    // //console.log(id + name);
    if (type == "Tracker") {
      //this.router.navigateByUrl("location?_dname="+name+"_id="+id);
      this.share_id = device;
      if (this.navId === undefined || this.navId != "locationHistory") {
        console.log("111111111133333");
        this.livetrack(id);
      }
    } else {
      this.router.navigateByUrl("account?_did=" + id + "." + name);
    }
  }

  constructor(
    public elementRef: ElementRef,
    public dialog: MdDialog,
    public _ngZone: NgZone,
    public snackBar: MdSnackBar,
    private contactService: ContactService,
    private router: Router,
    private activatedRoute: ActivatedRoute,
    private _flashMessagesService: FlashMessagesService,
    private injectData: DatainjectionService
  ) {
    let mapLanguage = localStorage.getItem("appLang");
    this.token_identifier = localStorage.getItem("referrer_token=");
    //console.log('mapLanguage',mapLanguage);
    if (mapLanguage == null || mapLanguage == undefined) {
      mapLanguage = "en";
    }
    if (mapLanguage == "sp") {
      mapLanguage = "es";
    }
    if (mapLanguage == "fa") {
      mapLanguage = "fas";
    }
    if (mapLanguage == "fr") {
      mapLanguage = "fr";
    }
    let tblid;
    let status = false;
    var cuTime = new Date();

    this.currentTime = moment(cuTime).format();

    this.activatedRoute.queryParams.subscribe((params: Params) => {
      this.navId = params["pageid"];

      if (this.navId === "locationHistory") {
        this.tabIndexValue = "2";
        this.showHistory = true;

        this.tab_1 = true;
        this.tab_2 = true;
      }
    });
  }
  fs: any;
  ls: any;
  emailid: any;
  or: any;
  speeed: any;
  mapp: boolean = true;
  mappp: boolean = true;
  latLongArr: any[] = [];
  latLongArr2: any[] = [];
  latlongObjArr = [];
  latlongObjArr2 = [];
  map = [];
  test2 = [];
  lat: any;
  lng: any;
  hismap: boolean = false;
  titleMarker: string;
  f: any;
  q: any;
  dev: any;
  drag: any;
  im: any;
  private socket;
  titleMarker2: any;
  Math: any;
  dname: any;
  ddid: any;
  mapOptions: any;
  checker: any;

  final: any;
  devicess: any;
  tblid: any;
  flag2: boolean = false;
  useridd: any;
  getData: any;
  fin: any;
  devicesss: any;
  custtype: any;
  cust: boolean = false;
  // selectedValue: string = this.foods[0].value;

  speedgauge() {
    gra();
    function gra() {
      var gauge = new RadialGauge({
        renderTo: "canvas-id",
        width: 300,
        height: 300,
        units: "Km/h",
        minValue: 0,
        startAngle: 90,
        ticksAngle: 180,
        valueBox: false,
        maxValue: 220,
        majorTicks: [
          "0",
          "20",
          "40",
          "60",
          "80",
          "100",
          "120",
          "140",
          "160",
          "180",
          "200",
          "220",
        ],
        minorTicks: 2,
        strokeTicks: true,
        highlights: [
          {
            from: 160,
            to: 220,
            color: "rgba(200, 50, 50, .75)",
          },
        ],
        colorPlate: "#fff",
        borderShadowWidth: 0,
        borders: false,
        needleType: "arrow",
        needleWidth: 2,
        needleCircleSize: 7,
        needleCircleOuter: true,
        needleCircleInner: false,
        animationDuration: 1500,
        animationRule: "linear",
      }).draw();
    }
  }
  timer: any;
  subscription: any;
  current_map: any;
  prev_map: any;
  MapChecker() {
    this.timer = Observable.timer(100, 100);
    this.subscription = this.timer.subscribe((t) => {
      this.current_map = window.localStorage.mapLoad_ID;
      if (!this.current_map) {
      } else if (this.current_map) {
        if (!this.prev_map) {
          this.MapLoad = true;
          if (this.current_map == "True") {
            if (this.navId === undefined || this.navId != "locationHistory") {
              console.log("111111111144444");
              this.livetrack(null);
            }

            this.prev_map = window.localStorage.mapLoad_ID;
            this.showButton = true;
          } else {
            // //console.log(window.localStorage.mapLoad_ID);
            if (this.navId === undefined || this.navId != "locationHistory") {
              console.log("111111115555555");
              this.livetrack(window.localStorage.mapLoad_ID);
            }

            this.prev_map = window.localStorage.mapLoad_ID;
            this.showButton = true;
          }
        } else if (this.prev_map == this.current_map) {
        } else if (this.current_map == "True") {
          this.MapLoad = true;
          if (this.navId === undefined || this.navId != "locationHistory") {
            console.log("11111111666666");
            this.livetrack(null);
          }

          this.prev_map = window.localStorage.mapLoad_ID;
          this.showButton = true;
        } else if (this.prev_map != this.current_map) {
          this.MapLoad = true;
          if (this.navId === undefined || this.navId != "locationHistory") {
            console.log("1111111777777");
            this.livetrack(window.localStorage.mapLoad_ID);
          }

          this.prev_map = window.localStorage.mapLoad_ID;
          this.showButton = true;
        }
      }
    });
  }

  mb: any;
  logoutbut: boolean;
  dealer: boolean;
  logo: any;
  text: any;
  datefrom = new Date();
  gaugeString: any = "PERCENTAGE";
  gaugeDataticks: any = "0,20,40,60,80,100";
  newFunction() {}

  ngOnInit() {
    debugger;
    window["angularComponentRef"] = { component: this, zone: this._ngZone };
    this.socket = this.injectData.getSocket_gps();

    this.socket.___id = Math.floor(Math.random() * 999999999) + 1;
    console.log("create_socket=>", this.socket.___id);
    this.socket.on("connect", function (this) {});

    this.socket_Notify = this.injectData.getSocket_notifIO();
    this.socket_Notify.on("connect", function (this) {});

    this.bsConfig = Object.assign(
      { dateInputFormat: "DD-MM-YYYY, h:mm:ss a" },
      { containerClass: this.colorTheme }
    );
    this.to = new Date().toISOString();
    var d = new Date();
    let a = d.setHours(0, 0, 0, 0);
    this.from = new Date(a).toISOString();

    this.reloadCOmponent = true;
    this.date1 = new Date().setHours(0, 0, 0);
    this.datefrom = new Date(this.date1);
    // //console.log(this.date1);
    this.logo = window.localStorage["logo"];
    this.text = window.localStorage["text"];

    this.superAdmin = JSON.parse(
      window.atob(window.localStorage.token.split(".")[1])
    ).isSuperAdmin;
    this.fs = JSON.parse(
      window.atob(window.localStorage.token.split(".")[1])
    ).fn;
    this.ls = JSON.parse(
      window.atob(window.localStorage.token.split(".")[1])
    ).ln;
    this.emailid = JSON.parse(
      window.atob(window.localStorage.token.split(".")[1])
    ).email;
    this.mb = JSON.parse(
      window.atob(window.localStorage.token.split(".")[1])
    ).phn;
    this.or = JSON.parse(
      window.atob(window.localStorage.token.split(".")[1])
    )._orgName;
    this.useridd = JSON.parse(
      window.atob(window.localStorage.token.split(".")[1])
    )._id;
    this.custtype = JSON.parse(
      window.atob(window.localStorage.token.split(".")[1])
    ).isDealer;
    var fuelvalue = JSON.parse(
      window.atob(window.localStorage.token.split(".")[1])
    ).fuel_unit;
    this.dealer_Permission = JSON.parse(
      window.atob(window.localStorage.token.split(".")[1])
    ).device_add_permission;
    this.dev_by_dashboard = localStorage.getItem("devDetail");
    this.adbtn = localStorage.getItem("dlrchk");
    if (fuelvalue == "PERCENTAGE") {
      this.gaugeString = "PERCENTAGE";
      this.gaugeDataticks = "0,20,40,60,80,100";
      // window.onload = function () {
      //   var gaugeElement = document.getElementById("fuelgauge");
      //   gaugeElement.setAttribute("data-units", "PERCENTAGE");
      //   gaugeElement.setAttribute("data-major-ticks", "0,20,40,60,80,100");
      //   gaugeElement.setAttribute("data-max-value", "100");
      // };
    } else {
      this.gaugeString = "LITRE";
    }

    if (this.superAdmin == true) {
      this.supadmin = this.useridd;
    }
    if (this.custtype == true) {
      this.dealerid = this.useridd;
    }

    if (this.custtype == true) {
      this.cust = true;
    }
    if (this.mb.charAt(0) == "n") {
      this.mb = " ";
    }
    if (window.localStorage["Custumer"] == "ON") {
      this.logoutbut = false;
      this.dealer = true;
    } else {
      this.logoutbut = true;
    }
    this.online = true;
    this.offline = false;
    window.localStorage["checker"] = "Data";

    this.activatedRoute.queryParams.subscribe((params: Params) => {
      this.getData = params["_dname"];
      if (this.getData == undefined || this.getData == null) {
        this.fin = null;
      } else {
        this.fin = this.getData.split("=")[1];
      }
    });

    if (this.token_identifier != undefined) {
      this.fin = null;
    }
    this.last_speed = localStorage.getItem("last_speed");
    this.getAllDevice();
    this.getGraphFunction();
    // this.getDeviceBYfilter('');
    this.getDevicebyIdComingFromDashboard();
    this.getGeofence_1();
    this.getGrp();
    this.modelChanged
      .debounceTime(2000) // wait 300ms after the last event before emitting last event
      .distinctUntilChanged() // only emit if value is different from previous value
      .subscribe((myInput) => {
        var searchObj = JSON.parse(myInput);
        this.myInput = searchObj.str;
        searchObj.identifier == "devSearch"
          ? this.getDeviceBYfilter("", "")
          : this.getGeofence_1();
      });
    this.getUserDetails();
  }

  // className:any;
  ngOnDestroy() {
    for (var e = 0; e < this.deviceToTrack.length; e++) {
      this.socket.removeAllListeners(this.deviceToTrack[e]);
      localStorage.removeItem("mapLoad_ID");
      localStorage.removeItem("mapLoad_Name");
    }

    localStorage.removeItem("devDetail");
    if (this.status_cmdq != undefined) {
      clearInterval(this.status_cmdq);
    }

    if (this.intervalTimeOut != undefined) {
      clearTimeout(this.intervalTimeOut);
    }

    window["angularComponentRef"] = null;
    if (this.socket_Notify) {
      this.socket_Notify.removeAllListeners();
    }
  }

  addpoi(lat) {
    var latlng = JSON.stringify(lat).substring(1, lat.length - 1);
    var latt = latlng.split(",")[0];
    var lng = latlng.split(",")[1];
    var reqlatlng = {
      lat: latt,
      long: lng,
    };
    let dialogRef = this.dialog.open(AddpoiBylocationComponent, {
      width: "650px",
      height: "700px",
      data: { deviceData: reqlatlng },
    });

    dialogRef.afterClosed().subscribe((result) => {});
  }
  disableSearch: boolean = false;
  DriverName;
  DriverNumber;
  ac;
  power;
  todaysOdo = 0;
  fuelConsumption = 0;
  getAllDevice() {
    if (this.dev_by_dashboard != null) {
      this.disableSearch = true;
      var search_1 = JSON.parse(this.dev_by_dashboard).vehicleId;
    }

    this.contactService
      .alldevices1(
        this.useridd,
        this.emailid,
        this.supadmin,
        this.dealerid,
        search_1
      )
      .subscribe(
        (res) => {
          this.deviceObj = [];
          var Alldevices = {
            id: "all",
            viewValue: "ALL Devices",
            iconType: "",
            deviceId: "",
          };
          if (res.devices.length == 1) {
            this.selectedDevice = res.devices[0]._id;
            this.parkingButtonShow =
              res.devices[0].theftAlert == null
                ? "grey"
                : res.devices[0].theftAlert == undefined
                ? "grey"
                : res.devices[0].theftAlert == true
                ? "green"
                : "red";
            this.DriverName = res.devices[0].driver_name;
            this.ac = res.devices[0].ac ? res.devices[0].ac : "NA";
            this.power = res.devices[0].power ? res.devices[0].power : "NA";
            this.todaysOdo = res.devices[0].today_odo
              ? res.devices[0].today_odo
              : 0;
            this.fuelConsumption =
              res.devices[0].Mileage && res.devices[0].total_odo
                ? res.devices[0].total_odo / res.devices[0].Mileage
                : 0;
            this.DriverNumber = res.devices[0].contact_number;
          }
          this.deviceObj.push(Alldevices);
          for (var i = 0; i < res.devices.length; i++) {
            Alldevices = {
              id: res.devices[i]._id,
              viewValue: res.devices[i].Device_Name
                ? res.devices[i].Device_Name
                : "",
              iconType: res.devices[i].iconType,
              deviceId: res.devices[i].Device_ID,
            };
            this.deviceObj.push(Alldevices);
          }

          this.final = res.devices;

          for (let i = 0; i < this.final.length; i++) {
            this.final[i]["checked"] = true;
            // this.deviceList = this.final;

            if (this.final[i].type_of_device == "Tracker") {
              let a = {
                value: this.final[i].Device_Name,
                viewValue: this.final[i].Device_Name,
                did: this.final[i].Device_ID,
                id: this.final[i]._id,
                user: this.final[i].user,
                email: this.final[i].Email_ID,
                deviceType: this.final[i].type_of_device,
                iconType: this.final[i].iconType,
              };

              this.foods.push(a);
            }
          }
          let that = this;
          if (this.navId === undefined || this.navId != "locationHistory") {
            this.livetrack1(this.fin);
          }

          for (let y = 0; y < this.foods.length; y++) {
            if (this.foods[y].did == this.fin) {
              this.new = this.foods[y];
            }
          }
          this._openMapComponet.isLocationTab =
            this.tabIndexValue == "2" ? false : true;
          this._openMapComponet.setMasterDeviceList(this.deviceList);
        },
        (err) => {}
      );
  }

  filterDevices(dlr) {
    if (dlr.length == 0) {
      this.foods = [];
    }
    if (dlr) {
      const filterdealerValue: any = dlr.toLowerCase();
      this.foods = [];
      if (this.navId === "locationHistory") {
        this.foods = this.masterFoods.filter((pp) => {
          if (pp.valueLocal) {
            var t = pp.valueLocal.indexOf(filterdealerValue);
            return t > -1;
          } else {
            return false;
          }
        });
        return this.foods;
      } else {
        this.foods = this.deviceList.filter((pp) => {
          var t = pp.Device_ID.toLocaleLowerCase().indexOf(
            filterdealerValue.toLocaleLowerCase()
          );
          return t > -1;
        });

        this.buindhistoryDevice = this.foods;

        return this.foods;
      }
    }
  }
  count: number = 0;
  iconSelector(status, iconType, msg) {
    // var tempSpeed = msg.speed;
    // var tempIgn = msg.ignition;
    var iconUrl = "";
    // if(status !="OUT OF REACH"){
    //   if (((msg.speed != undefined) && (msg.speed != null)) && ((msg.ignition != null)&&(msg.ignition != undefined))) {
    //     if (parseInt(msg.ignition) == 0) {
    //       status = "STOPPED"
    //     }
    //     else if (msg.ignition == "1" && parseInt(msg.speed) > 0) {
    //       status = "RUNNING";
    //     } else {
    //       status = "IDLING"
    //     }
    //   }
    // }

    if (status == "OUT OF REACH") {
      if (iconType == "bike") {
        iconUrl = "/assets/images/liveTrackIcons/obike.png";
        return iconUrl;
      }
      if (iconType == "car") {
        iconUrl = "/assets/images/liveTrackIcons/ocar.png";
        return iconUrl;
      } else if (iconType == "bus") {
        iconUrl = "/assets/images/liveTrackIcons/obus.png";
        return iconUrl;
      } else if (iconType == "truck") {
        iconUrl = "/assets/images/liveTrackIcons/otruck.png";
        return iconUrl;
      } else if (iconType == "tractor") {
        iconUrl = "/assets/images/liveTrackIcons/otractor.png";
        return iconUrl;
      } else if (iconType == "jcb") {
        iconUrl = "/assets/images/liveTrackIcons/ourjcb.png";
        return iconUrl;
      } else if (iconType == "ambulance") {
        iconUrl = "/assets/images/liveTrackIcons/ambulance_b.png";
        return iconUrl;
      } else {
        iconUrl = "/assets/images/liveTrackIcons/user_b.png";
        return iconUrl;
      }
    } else if (status == "STOPPED") {
      if (iconType == "bike") {
        iconUrl = "/assets/images/liveTrackIcons/sbike.png";
        return iconUrl;
      } else if (iconType == "car") {
        iconUrl = "/assets/images/liveTrackIcons/scar.png";
        return iconUrl;
      } else if (iconType == "bus") {
        iconUrl = "/assets/images/liveTrackIcons/sbus.png";
        return iconUrl;
      } else if (iconType == "truck") {
        iconUrl = "/assets/images/liveTrackIcons/struck.png";
        return iconUrl;
      } else if (iconType == "tractor") {
        iconUrl = "/assets/images/liveTrackIcons/stractor.png";
        return iconUrl;
      } else if (iconType == "jcb") {
        iconUrl = "/assets/images/liveTrackIcons/stoppedjcb.png";
        return iconUrl;
      } else if (iconType == "ambulance") {
        iconUrl = "/assets/images/liveTrackIcons/ambulance_r.png";
        return iconUrl;
      } else {
        iconUrl = "/assets/images/liveTrackIcons/user_r.png";
        return iconUrl;
      }
    } else if (status == "RUNNING") {
      if (iconType == "bike") {
        iconUrl = "/assets/images/liveTrackIcons/rbike.png";
        return iconUrl;
      } else if (iconType == "car") {
        iconUrl = "/assets/images/liveTrackIcons/rcar.png";
        return iconUrl;
      } else if (iconType == "bus") {
        iconUrl = "/assets/images/liveTrackIcons/rbus.png";
        return iconUrl;
      } else if (iconType == "truck") {
        iconUrl = "/assets/images/liveTrackIcons/rtruck.png";
        return iconUrl;
      } else if (iconType == "tractor") {
        iconUrl = "/assets/images/liveTrackIcons/rtractor.png";
        return iconUrl;
      } else if (iconType == "jcb") {
        iconUrl = "/assets/images/liveTrackIcons/runningjcb.png";
        return iconUrl;
      } else if (iconType == "ambulance") {
        iconUrl = "/assets/images/liveTrackIcons/ambulance_g.png";
        return iconUrl;
      } else {
        iconUrl = "/assets/images/liveTrackIcons/user_g.png";
        return iconUrl;
      }
    } else if (status == "IDLING") {
      if (iconType == "bike") {
        iconUrl = "/assets/images/liveTrackIcons/ibike.png";
        return iconUrl;
      } else if (iconType == "car") {
        iconUrl = "/assets/images/liveTrackIcons/icar.png";
        return iconUrl;
      } else if (iconType == "bus") {
        iconUrl = "/assets/images/liveTrackIcons/ibus.png";
        return iconUrl;
      } else if (iconType == "truck") {
        iconUrl = "/assets/images/liveTrackIcons/itruck.png";
        return iconUrl;
      } else if (iconType == "tractor") {
        iconUrl = "/assets/images/liveTrackIcons/itractor.png";
        return iconUrl;
      } else if (iconType == "jcb") {
        iconUrl = "/assets/images/liveTrackIcons/idlingjcb.png";
        return iconUrl;
      } else if (iconType == "ambulance") {
        iconUrl = "/assets/images/liveTrackIcons/ambulance_y.png";
        return iconUrl;
      } else {
        iconUrl = "/assets/images/liveTrackIcons/user_y.png";
        return iconUrl;
      }
    } else if (status == "NO DATA") {
      if (iconType == "bike") {
        iconUrl = "/assets/image/no_data.png";
        return iconUrl;
      } else if (iconType == "car") {
        iconUrl = "/assets/image/no_data.png";
        return iconUrl;
      } else if (iconType == "bus") {
        iconUrl = "/assets/image/no_data.png";
        return iconUrl;
      } else if (iconType == "truck") {
        iconUrl = "/assets/image/no_data.png";
        return iconUrl;
      } else if (iconType == "tractor") {
        iconUrl = "/assets/image/no_data.png";
        return iconUrl;
      } else if (iconType == "jcb") {
        iconUrl = "/assets/image/no_data.png";
        return iconUrl;
      } else {
        iconUrl = "/assets/images/liveTrackIcons/user_g.png";
        return iconUrl;
      }
    }
  }

  playPause: boolean = true;
  startCreatingFlightPath: boolean = false;
  createTrip(dev) {
    console.log("devicedevicedevice=>", dev);

    var DeviceObj = JSON.parse(localStorage.getItem("devDetail"));

    var vehicleLatLng = {
      lat: this.latToPass,
      long: this.longToPass,
    };

    var tttt = this;

    DeviceObj["LatLng"] = vehicleLatLng;

    let dialogRef = this.dialog.open(CreateTripComponent, {
      width: "900px",
      data: DeviceObj,
    });

    dialogRef.afterClosed().subscribe((result) => {
      var parseTripInfoString = JSON.parse(result);

      if (parseTripInfoString.msg == "created") {
        tttt.playPause = !tttt.playPause;
        this.showSocketData = false;
        let action: any;
        this.snackBar.open("Trip Created", action, {
          duration: 5000,
        });
        tttt.getDevicebyId();
        // tttt.drawFlightPath(result) ;
      }
    });
  }

  endTrip() {
    // //console.log("Inside function");
    var bUrl = "https://www.oneqlik.in/user_trip/updatePlantrip";
    var userId = this.useridd;
    var startLat = this.EndTripStartLat;
    var startLong = this.EndTripStartLong;
    var endLat = this.latToPass;
    var endLong = this.longToPass;
    var duration = this.ETA;
    var distance = google.maps.geometry.spherical.computeDistanceBetween(
      new google.maps.LatLng(startLat, startLong),
      new google.maps.LatLng(this.latToPass, this.longToPass)
    );
    // //console.log('distance',distance);
    var trip_id = this.tripId;

    var payload = {
      user: userId,
      device: this.IMEI,
      start_loc: {
        lat: startLat,
        long: startLong,
      },
      end_loc: {
        lat: endLat,
        long: endLong,
      },
      duration: duration,
      distance: distance,
      trip_status: "completed",
      trip_id: trip_id,
    };

    this.contactService.endTrip(payload).subscribe(
      (res) => {
        this.playPause = !this.playPause;

        let action: any;
        this.snackBar.open("Current Trip Completed", action, {
          duration: 5000,
        });

        this.ngOnInit();
      },
      (err) => {
        // //console.log(err);
      }
    );
  }
  IMEI: any;
  getDevicebyId() {
    var DeviceObj = JSON.parse(localStorage.getItem("devDetail"));
    if (DeviceObj != undefined) {
      // //console.log('DeviceObj',DeviceObj);
      this.contactService.getdevById(DeviceObj.vehicleId).subscribe(
        (res: any) => {
          console.log("lastTripStatus", res);
          // this.getLastTrip();\
          var tempObj = JSON.parse(res["_body"]);
          this.distanceVariation = tempObj.distanceVariation
            ? tempObj.distanceVariation
            : undefined;

          this.IMEI = tempObj._id;

          this.getLastTrip(this.IMEI);
        },
        (err) => {
          //console.log(err);
        }
      );
    } else {
      //console.log('No trip found');
    }
  }

  getLastTrip(imei) {
    console.log("IMEI==>", imei);

    this.contactService
      .getLastTripStatus("last_trip", "Started", imei)
      .subscribe(
        (res) => {
          console.log("lastTripStatus", res);
          if (res.message != "No Trip Found") {
            this.playPause = false;
            this.tripId = res[0]._id;
            this.drawFlightPath(JSON.stringify(res));
          } else {
            this.playPause = true;
          }
          var outerThis = this;
          this.deviceList.filter(function (colHilight, i) {
            if (colHilight.Device_ID === imei) {
              outerThis.deviceList[i].playPause = outerThis.playPause;
            }
          });
        },
        (err) => {
          //console.log(err);
        }
      );
  }

  drawFlightPath(tripInfo) {
    // //console.log('tripInfo',this.mapNew);
    this.directionsService = new google.maps.DirectionsService();
    this.directionsDisplay = new google.maps.DirectionsRenderer({
      // draggable: true,
      map: this.mapNew,
      suppressMarkers: true,
    });
    google.maps.event.addListener(
      this.directionsDisplay,
      "click",
      function (h) {
        // //console.log(h.latLng.lat(),h.latLng.lng());
      }
    );
    // this.computeTotalDistance(this.directionsDisplay.getDirections());

    this.directionsDisplay.addListener("directions_changed", function () {
      // this.computeTotalDistance(this.directionsDisplay.getDirections());
    });

    var sourceLat;
    var sourceLong;
    var getDestPoint = JSON.parse(tripInfo);
    // //console.log('getDestPoint',getDestPoint);
    if (this.latToPass == undefined) {
      sourceLat = getDestPoint[0].start_lat;
      this.EndTripStartLat = sourceLat;
    } else {
      sourceLat = this.latToPass;
      this.EndTripStartLat = sourceLat;
    }
    if (this.longToPass == undefined) {
      sourceLong = getDestPoint[0].start_long;
      this.EndTripStartLong = sourceLong;
    } else {
      sourceLong = this.longToPass;
      this.EndTripStartLong = sourceLong;
    }
    var sourcePoint = new google.maps.LatLng(sourceLat, sourceLong);
    var that = this;
    var end_location_lat = getDestPoint.reponse
      ? getDestPoint.reponse.doc.end_lat
      : getDestPoint[0].end_lat;
    var end_location_long = getDestPoint.reponse
      ? getDestPoint.reponse.doc.end_long
      : getDestPoint[0].end_long;
    //  //console.log(sourceLat, sourceLong,end_location_lat,end_location_long);
    var destPoint = new google.maps.LatLng(end_location_lat, end_location_long);
    var distance = google.maps.geometry.spherical.computeDistanceBetween(
      new google.maps.LatLng(sourceLat, sourceLong),
      new google.maps.LatLng(end_location_lat, end_location_long)
    );
    this.directionsService.route(
      {
        origin: sourcePoint,
        destination: destPoint,
        travelMode: "DRIVING",
        avoidTolls: true,
      },
      function (response, status) {
        if (status === "OK") {
          that.ETA = response.routes[0]
            ? response.routes[0].legs[0].duration.text
            : "";
          // //console.log("response",that.ETA);
          that.directionsDisplay.setDirections(response);
          that.ShowInfo(that.ETA, distance);
        } else {
          alert("Could not display directions due to: " + status);
        }
      }
    );
  }

  ShowInfo(eta, distance) {
    var distanceInKm = distance / 1000;
    let d =
      '<div class="infoB">' +
      '<p class="DeviceHead1">' +
      "TRIP INFO" +
      "</p>" +
      '<div class="row rowTwo">' +
      '<div class="col-sm-5">' +
      "Total Distance" +
      "</div>" +
      '<div class="col-sm-7 leftPadding">' +
      distanceInKm.toFixed(2) +
      " " +
      "Kms." +
      "</div>" +
      "</div>" +
      '<div class="row rowOne">' +
      '<div class="col-sm-5">' +
      "ETA" +
      "</div>" +
      '<div class="col-sm-7 leftPadding">' +
      eta +
      "</div>" +
      "</div>" +
      "</div>";

    // var customTxt = `<div style="display: contents;background: #ebebeb;border: 1px solid #dcd4d4; box-shadow: 2px 2px #cabdbd;"> <p style="border-bottom: 1px solid #c8c3c3;text-align: center;margin-bottom: 0px;">Detail</p> <table> <tbody> <tr style="text-align: center;border-bottom: 1px solid #c8c3c3;"> <td title="Total Distance" style="padding-left: 1rem"><i class="fa fa-road" aria-hidden="true"></i></td> <td style="padding-left: 1rem">`+this.total_dis+`</td> <td style="padding-left: 1rem">Kms.</td> </tr> <tr style="text-align: center;border-bottom: 1px solid #c8c3c3;"> <td title="Running Time" style="padding-left: 1rem"><i style="color:green" class="fas fa-car"></i></td> <td style="padding-left: 1rem">`+'NA'+`</td> <td style="padding-left: 1rem">Hrs.</td> </tr> <tr style="text-align: center;border-bottom: 1px solid #c8c3c3;"> <td title="Stoppage Time" style="padding-left: 1rem"><i style="color:red" class="fas fa-car"></i></td> <td style="padding-left: 1rem">`+this.ideal_time+`</td> <td style="padding-left: 1rem">Min.</td> </tr> <tr style="text-align: center;border-bottom: 1px solid #c8c3c3;"> <td title="Average Speed" style="padding-left: 1rem"><i class="fas fa-tachometer-alt" style="color:green"></i></td> <td style="padding-left: 1rem">`+this.avg_speed+`</td> <td style="padding-left: 1rem">Km/Hr</td> </tr> <tr style="text-align: center;border-bottom: 1px solid #c8c3c3;"> <td title="No. of Parking" style="padding-left: 1rem"><i class="fas fa-parking"></i></td> <td style="padding-left: 1rem">`+this.stoppageCount+`</td> <td style="padding-left: 1rem"></td> </tr> <tr style="text-align: center;border-bottom: 1px solid #c8c3c3;"> <td title="Max Speed" style="padding-left: 1rem"><i class="fa fa-tachometer-alt" style="color:red" aria-hidden="true"></i></td> <td style="padding-left: 1rem">`+this.maxSpeedd+`</td> <td style="padding-left: 1rem">Km/Hr</td> </tr> <tr style="text-align: center;border-bottom: 1px solid #c8c3c3;"> <td title="Sudden Break" style="padding-left: 1rem"><i class="fas fa-stop"></i></td> <td style="padding-left: 1rem">`+'NA'+`</td> <td style="padding-left: 1rem"></td> </tr> <tr style="text-align: center;border-bottom: 1px solid #c8c3c3;"> <td title="Sudden Acceleration" style="padding-left: 1rem"><i class="fa fa-flag-checkered" aria-hidden="true"></i></td> <td style="padding-left: 1rem">`+'NA'+`</td> <td style="padding-left: 1rem"></td> </tr> <tr style="text-align: center;border-bottom: 1px solid #c8c3c3;"> <td title="Fuel Consumption" style="padding-left: 1rem"><i class="fas fa-gas-pump"></i></td> <td style="padding-left: 1rem">`+'NA'+`</td> <td style="padding-left: 1rem">Liter</td> </tr> </tbody> </table> </div>`
    // that.mapNew.controls[google.maps.ControlPosition.LEFT_TOP].push(d);
    var centerControlDiv = document.createElement("div");
    var centerControl = new CenterControl(centerControlDiv, this.mapNew, d);
    centerControl.zIndex = 1;
    this.mapNew.controls[google.maps.ControlPosition.BOTTOM_CENTER].push(
      centerControlDiv
    );

    function CenterControl(controlDiv, map, text) {
      // Set CSS for the control border.
      var controlUI = document.createElement("div");
      controlUI.style.backgroundColor = "#fff";
      controlUI.style.border = "2px solid #fff";
      controlUI.style.borderRadius = "3px";
      controlUI.style.boxShadow = "0 2px 6px rgba(0,0,0,.3)";
      controlUI.style.cursor = "pointer";
      controlUI.style.marginBottom = "22px";
      controlUI.style.textAlign = "left";
      controlUI.style.marginLeft = "11px";
      controlUI.style.opacity = "0.9";
      controlDiv.appendChild(controlUI);

      // Set CSS for the control interior.
      var controlText = document.createElement("div");
      controlText.style.color = "rgb(25,25,25)";
      controlText.style.fontFamily = "Roboto,Arial,sans-serif";
      controlText.style.fontSize = "16px";
      controlText.style.lineHeight = "38px";
      controlText.style.paddingLeft = "5px";
      controlText.style.paddingRight = "5px";
      controlText.innerHTML = text;
      controlUI.appendChild(controlText);

      // Setup the click event listeners: simply set the map to Chicago.
    }
  }

  idlePlot(fromtime, totime, deviceObjectid, min_time, map) {
    this.contactService
      .ignitionPoint(this.useridd, fromtime, totime, deviceObjectid, min_time)
      .subscribe((res) => {
        var ignPoint = res;
        //console.log(ignPoint);

        if (ignPoint.length > 0) {
          for (var p = 0; p < ignPoint.length; p++) {
            let idelImage = new google.maps.MarkerImage(
              "http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=" +
                "I" +
                "|FFFF00|000000"
            );
            let infowindow_idel = new google.maps.InfoWindow();
            const myOptions = {
              zoom: 15,
              center: new google.maps.LatLng(18.602941, 73.777147),
              mapTypeId: google.maps.MapTypeId.ROADMAP,
            };

            // isMapInit = true;

            // ============================

            var marker_idle: any, k: any;
            var l: number;

            var latitude_idle = ignPoint[p].lat;
            var longitude_idle = ignPoint[p].long;
            var arrivalTime_idle = new Date(
              ignPoint[p].start_time
            ).toLocaleString();

            var departureTime_idle = new Date(
              ignPoint[p].end_time
            ).toLocaleString();

            // var fd_idle = new Date(arrivalTime_idle).getTime();
            // var td_idle = new Date(departureTime_idle).getTime();
            // var time_difference_idle = td_idle - fd_idle;
            // var total_min_idle = time_difference_idle / 60000;
            // var hours = total_min_idle / 60
            // var minutes = (hours - rhours) * 60;
            // var rhours = Math.floor(hours);
            // var rminutes = Math.round(minutes);

            var Durations_idle = this.millisecondConversion(
              ignPoint[p].idle_time
            );

            marker_idle = new google.maps.Marker({
              position: new google.maps.LatLng(
                ignPoint[p].lat,
                ignPoint[p].long
              ),
              map: map,
              icon: idelImage,
            });

            var content_idle =
              "<div ><div> Idle Start-: " +
              arrivalTime_idle +
              "</div><br><div>Idle End-: " +
              departureTime_idle +
              "</div><br><div>Time Duration (HH:MM:SS)-: " +
              Durations_idle +
              " </div></br><div> Latitude-: " +
              latitude_idle +
              " </div></br><div> Longitude-: " +
              longitude_idle +
              " </div><div>";

            google.maps.event.addListener(
              marker_idle,
              "click",
              (function (marker, content_idle, infowindow_idel) {
                return function () {
                  geocodePosition(marker.getPosition(), function (result) {
                    infowindow_idel.setContent(content_idle);
                    infowindow_idel.open(map, marker, content_idle);
                  });
                };
              })(marker_idle, content_idle, infowindow_idel)
            );
          }

          marker_idle.setMap(map);
        }
      });

    function geocodePosition(pos, callback) {
      var geocoder = new google.maps.Geocoder();
      geocoder.geocode(
        {
          latLng: pos,
        },
        function (responses) {
          callback(responses[0].formatted_address);
        }
      );
    }
  }

  millisecondConversion(duration) {
    // //console.log('duration=>',duration)
    // //console.log(typeof(duration));
    //  var milliseconds = ((duration % 1000) / 100);
    var seconds = Math.floor((duration / 1000) % 60);
    var minutes = Math.floor((duration / (1000 * 60)) % 60);
    var hours = Math.floor((duration / (1000 * 60 * 60)) % 24);

    hours = hours < 10 ? 0 + hours : hours;
    minutes = minutes < 10 ? 0 + minutes : minutes;
    seconds = seconds < 10 ? 0 + seconds : seconds;
    // //console.log(hours, minutes,seconds);
    return hours + ":" + minutes + ":" + seconds;
  }

  // testMap(){

  //   var markerPoint = new google.maps.LatLng(18.602941, 73.777147) ;
  //   const myOptions = {
  //     zoom: 15,
  //     center: new google.maps.LatLng(18.602941, 73.777147),
  //     mapTypeId: google.maps.MapTypeId.ROADMAP
  //   };

  //  var testmap = new google.maps.Map(document.getElementById('testmap'), myOptions);

  //   var icon1 = {
  //     url: "./assets/image/activeCar.png", // url
  //     scaledSize: new google.maps.Size(50, 50), // scaled size

  //   };
  //   var marker = new google.maps.Marker({
  //     position: markerPoint,
  //     map: testmap,
  //     icon: icon1,
  //     title: "Vehicle"
  //   });

  // }

  AllVeh: any = [
    { status: "Running", totalCount: "0" },
    { status: "Idle", totalCount: "0" },
    { status: "Stopped", totalCount: "0" },
    { status: "Inactive", totalCount: "0" },
    { status: "No data", totalCount: "0" },
  ];

  deviceData = [
    {
      vehIconColor: "red",
      vehNo: "test 7681",
      lastSpeed: "50",
      gpsIconColor: "green",
      acIconColor: "grey",
      powerIconColor: "blue",
      gsmIconColor: "red",
      ignIconColor: "green",
    },
    {
      vehIconColor: "green",
      vehNo: "test 7682",
      lastSpeed: "50",
      gpsIconColor: "grey",
      acIconColor: "green",
      powerIconColor: "purple",
      gsmIconColor: "blue",
      ignIconColor: "green",
    },
    {
      vehIconColor: "grey",
      vehNo: "test 7683",
      lastSpeed: "50",
      gpsIconColor: "blue",
      acIconColor: "red",
      powerIconColor: "blue",
      gsmIconColor: "grey",
      ignIconColor: "green",
    },
    {
      vehIconColor: "blue",
      vehNo: "test 7684",
      lastSpeed: "50",
      gpsIconColor: "green",
      acIconColor: "grey",
      powerIconColor: "red",
      gsmIconColor: "red",
      ignIconColor: "green",
    },
    {
      vehIconColor: "red",
      vehNo: "test 7685",
      lastSpeed: "50",
      gpsIconColor: "blue",
      acIconColor: "grey",
      powerIconColor: "red",
      gsmIconColor: "red",
      ignIconColor: "green",
    },
    {
      vehIconColor: "blue",
      vehNo: "test 7686",
      lastSpeed: "50",
      gpsIconColor: "red",
      acIconColor: "grey",
      powerIconColor: "green",
      gsmIconColor: "red",
      ignIconColor: "green",
    },
    {
      vehIconColor: "grey",
      vehNo: "test 7687",
      lastSpeed: "50",
      gpsIconColor: "blue",
      acIconColor: "grey",
      powerIconColor: "red",
      gsmIconColor: "red",
      ignIconColor: "green",
    },
    {
      vehIconColor: "green",
      vehNo: "test 7688",
      lastSpeed: "50",
      gpsIconColor: "red",
      acIconColor: "green",
      powerIconColor: "blue",
      gsmIconColor: "red",
      ignIconColor: "green",
    },
    {
      vehIconColor: "red",
      vehNo: "test 7689",
      lastSpeed: "50",
      gpsIconColor: "blue",
      acIconColor: "grey",
      powerIconColor: "grey",
      gsmIconColor: "red",
      ignIconColor: "red",
    },
    {
      vehIconColor: "blue",
      vehNo: "test 7610",
      lastSpeed: "50",
      gpsIconColor: "green",
      acIconColor: "grey",
      powerIconColor: "blue",
      gsmIconColor: "red",
      ignIconColor: "green",
    },
    {
      vehIconColor: "grey",
      vehNo: "test 7611",
      lastSpeed: "50",
      gpsIconColor: "green",
      acIconColor: "grey",
      powerIconColor: "blue",
      gsmIconColor: "red",
      ignIconColor: "green",
    },
    {
      vehIconColor: "green",
      vehNo: "test 7612",
      lastSpeed: "50",
      gpsIconColor: "red",
      acIconColor: "grey",
      powerIconColor: "red",
      gsmIconColor: "red",
      ignIconColor: "green",
    },
  ];
  myInput: any;

  getVehColor(colorid, devicestatus) {
    if (colorid == "vehStatus") {
      var devStatus = devicestatus.split(" ");
      var styleColor =
        devStatus[0] == "OUT"
          ? "blue"
          : devStatus[0] == "RUNNING"
          ? "green"
          : devStatus[0] == "STOPPED"
          ? "red"
          : devStatus[0] == "IDLING"
          ? "yellow"
          : "grey";

      return styleColor;
    }

    if (colorid == "gpsStatus") {
      var styleColor =
        devicestatus == 0 ? "red" : devicestatus == 1 ? "green" : "grey";
      return styleColor;
    }

    if (colorid == "acStatus") {
      var styleColor =
        devicestatus == 0 ? "red" : devicestatus == 1 ? "green" : "grey";
      return styleColor;
    }

    if (colorid == "ignStatus") {
      var styleColor =
        devicestatus == 0 ? "red" : devicestatus == 1 ? "green" : "grey";
      return styleColor;
    }

    if (colorid == "powerStatus") {
      var styleColor =
        devicestatus == 0 ? "red" : devicestatus == 1 ? "green" : "grey";
      return styleColor;
    }

    if (colorid == "gsmStatus") {
      var styleColor =
        devicestatus == 0 ? "red" : devicestatus == 1 ? "green" : "grey";
      return styleColor;
    }
  }

  getGraphFunction() {
    this.contactService
      .getDashboard(
        this.emailid,
        this.from,
        this.to,
        this.useridd,
        this.groupId,
        this.supadmin,
        this.dealerid
      )
      .subscribe((data) => {
        this.devicess = data;
        this.total_vech = this.devicess.Total_Vech;
        this.idle_vech = this.devicess["Ideal Devices"];
        this.off_vech = this.devicess["OFF Devices"];
        this.maintanance = this.devicess["Maintance Device"];
        this.expiredDevices = this.devicess["expire_status"];
        this.OutOfReach = this.devicess["OutOfReach"];
        this.no_data = this.devicess["no_data"];
        this.Running = this.devicess["running_devices"];
        this.idle_duration = this.devicess.idle_duration;
        this.off_duration = this.devicess.off_duration;

        let a =
          this.idle_vech + this.off_vech + this.maintanance + this.OutOfReach;
        let b = this.total_vech - a;

        this.AllVeh[0].totalCount = this.Running;
        this.AllVeh[1].totalCount = this.idle_vech;
        this.AllVeh[2].totalCount = this.off_vech;
        this.AllVeh[3].totalCount = this.OutOfReach;
        this.AllVeh[4].totalCount = this.no_data;
      });
  }
  groupId: any;
  skip: number = 0;
  limit: number = 100;
  firstcall: boolean = false;
  lastcall: boolean = true;
  devReady: boolean = true;
  groups = [];
  masterFoods = [];
  getDeviceBYfilter(i, iden) {
    this.currStatus = i;
    if (i == 6) {
      this.skip = 0;
    }
    var vehStatus: string;
    if (i != undefined) {
      vehStatus =
        i.toUpperCase() == "INACTIVE"
          ? "OUT OF REACH"
          : i.toUpperCase() == "IDLE"
          ? "IDLING"
          : i.toUpperCase();
    } else {
      vehStatus = null;
    }

    var status_1 = false;
    if (iden === "tclick") {
      this.showSocketData = false;
    } else {
      this.showSocketData = true;
    }
    this.deviceList = [];
    this.foods = [];
    //console.log('this.navId',this.navId);
    if (this.navId == "locationHistory") {
      iden = "tclick";
      this.devReady = false;
      this.limit = 10000;
    }

    // //console.log('limitfgdfgdfgdgdgdgfdgfdgdgfdgfdgdfg',this.limit);
    this.contactService
      .getDeviceByFilter_dash(
        vehStatus,
        this.emailid,
        this.useridd,
        this.skip,
        this.limit,
        this.myInput,
        this.supadmin,
        this.dealerid,
        status_1
      )
      .subscribe((res) => {
        console.log("INside devList");
        var aaaa = res;
        this.deviceList = aaaa.devices;
        this.devReady = true;
        if (this.deviceList.length === 0) {
          this.lastcall = false;
          this.firstcall = true;
        }
        this.foods = [];

        for (var k = 0; k < this.deviceList.length; k++) {
          this.deviceList[k]["playPause"] = true;
          this.deviceList[k]["checked"] = true;
          if (iden === "tclick") {
            if (this.deviceList[k].type_of_device == "Tracker") {
              let a = {
                value: this.deviceList[k].Device_Name,
                valueLocal: this.deviceList[k].Device_Name
                  ? this.deviceList[k].Device_Name.toLowerCase()
                  : "",
                viewValue: this.deviceList[k].Device_Name,
                did: this.deviceList[k].Device_ID,
                Device_ID: this.deviceList[k].Device_ID,
                id: this.deviceList[k]._id,
                user: this.deviceList[k].user,
                email: this.deviceList[k].Email_ID,
                deviceType: this.deviceList[k].type_of_device,
                iconType: this.deviceList[k].iconType,
                //  checked: true
              };
              this.foods.push(a);
              if (k === this.deviceList.length - 1) {
                console.log("1111111110100000");
                if (this.navId != "locationHistory") {
                  this.showSocketData = false;
                }
                this.livetrack(null);
              }
            }
          }
        }
        if (this.deviceList.length == 1) {
          this.selectedDevice = this.deviceList[0]._id;
          this.parkingButtonShow =
            this.deviceList[0].theftAlert == null
              ? "grey"
              : this.deviceList[0].theftAlert == undefined
              ? "grey"
              : this.deviceList[0].theftAlert == true
              ? "green"
              : "red";
          this.DriverName = this.deviceList[0].driver_name;
          this.ac = this.deviceList[0].ac ? this.deviceList[0].ac : "NA";
          this.DriverNumber = this.deviceList[0].contact_number;
        }
        this.selectAllVehicles({ checked: true });
      });

    this.masterFoods = this.foods;
  }

  getDevicebyIdComingFromDashboard() {
    this.buindhistoryDevice = [];
    var DeviceObj = JSON.parse(localStorage.getItem("devDetail"));
    if (DeviceObj != undefined) {
      this.contactService.getdevById(DeviceObj.vehicleId).subscribe(
        (res: any) => {
          var tempObj = JSON.parse(res["_body"]);
          this.distanceVariation = tempObj.distanceVariation
            ? tempObj.distanceVariation
            : undefined;
          tempObj["checked"] = true;
          this.temptrackingDev = tempObj.Device_ID;
          this.buindhistoryDevice.push(tempObj);
          this.deviceList.push(tempObj);
        },
        (err) => {}
      );
    } else {
      this.getDeviceBYfilter("", "");
    }
  }

  next() {
    this.lastcall = false;
    this.skip += 1;
    this.getDeviceBYfilter(this.currStatus, "tclick");
  }

  refresh() {
    this.getGraphFunction();
    this.getDeviceBYfilter(this.currStatus, "");
  }

  pre() {
    if (this.skip > 0) {
      this.skip -= 1;
      this.getDeviceBYfilter(this.currStatus, "tclick");
      this.lastcall = false;
    } else {
      this.lastcall = true;
      this.firstcall = false;
    }
  }

  geoArr: any;
  getGeofence_1() {
    this.geoArr = [];
    this.contactService.getallgeofence(this.useridd).subscribe((data) => {
      this.geoArr = data;
    });
  }
  currentPage: any = 1;

  getTab(ev) {
    this.currentPage = ev;
    this.playingHistory = false;
    this.flag = "";
    this.showHistory = false;
    var outerThis = this;
    if (ev == 0 || ev == 1) {
      clearTimeout(this.start);
      this.historyDataCondition = false;
      if (ev == 0) {
        this.headingName = "Live Tracking";
        this.showSocketData = true;
        if (this.navId === undefined || this.navId != "locationHistory") {
          console.log("1111111111-11-");
          this.livetrack(this.temptrackingDev);
        }

        // this.refresh_map();
      }
      if (ev == 1) {
        this.headingName = "Geofences";
        // this.refresh_map();
        this.showSocketData = false;
      }
    }
    if (ev == 2) {
      this.historyDataCondition = true;
      this.showHistory = true;

      this.showSocketData = false;
      this.headingName = "History Tracking";
      this.tempMapHistory = [];
      this.dataArrayCoords = [];
      if (this.buindhistoryDevice != undefined) {
        if (this.buindhistoryDevice.length != 0) {
          this.deviceName = this.buindhistoryDevice[0].Device_Name;
        }
        this.deviceSelect = this.buindhistoryDevice.length
          ? this.buindhistoryDevice
          : this.deviceSelect;
      }
      this.disableSearch = true;
      navigator.geolocation.getCurrentPosition(function (position) {
        var myOptions = {
          zoom: 18,
          center: {
            lat: position.coords.latitude,
            lng: position.coords.longitude,
          },
          mapTypeId: google.maps.MapTypeId.ROADMAP,
        };
        console.log("manoj 3");
        var mapHistory = new google.maps.Map(
          document.getElementById("map2"),
          myOptions
        );

        var marker = new google.maps.Marker({
          center: {
            lat: position.coords.latitude,
            lng: position.coords.longitude,
          },
          map: mapHistory,
          title: "Your current location!",
        });
      });
    }
    this._openMapComponet.toggleMapDetails(ev == 2 ? false : true);
  }

  thicknessVal: any = "2px";
  thicknessArr: any = [
    "2px",
    "3px",
    "4px",
    "5px",
    "6px",
    "7px",
    "8px",
    "9px",
    "10px",
  ];
  parkingColor: boolean = false;
  idleColor: boolean = false;
  dataColor: boolean = false;

  changeColor(id) {
    if (id === "parking") {
      this.parkingColor = !this.parkingColor;
    }
    if (id === "idle") {
      this.idleColor = !this.idleColor;
    }
    if (id === "datapoint") {
      this.dataColor = !this.dataColor;
    }
    this._openMapComponet.historyMode = {
      isParking: this.parkingColor,
      isIdle: this.idleColor,
      isPoints: this.dataColor,
    };
  }

  removetracks(id1, arrIndex) {
    //console.log('id1', id1);
    //console.log('arrIndex', arrIndex);
    if (id1 === "all" && arrIndex == null) {
      this.tempMapHistory = [];
      this.playingHistory = false;
      this.showTable = false;
      this.coloumnClicked = false;
    }
    if (id1 === "single") {
      this.tempMapHistory.splice(arrIndex, 1);
      //console.log('this.tempMapHistory', this.tempMapHistory);
      if (this.tempMapHistory.length === 0) {
        this.playingHistory = false;
        this.showTable = false;
        this.coloumnClicked = false;
      }
    }
    this._openMapComponet.removeHistoryPath(
      id1 === "single" ? false : true,
      arrIndex
    );
  }

  refresh_map() {
    navigator.geolocation.getCurrentPosition(function (position) {
      var myOptions = {
        zoom: 18,
        center: {
          lat: position.coords.latitude,
          lng: position.coords.longitude,
        },
        mapTypeId: google.maps.MapTypeId.ROADMAP,
      };
      console.log("manoj 4");
      var mapHistory = new google.maps.Map(
        document.getElementById("map2"),
        myOptions
      );

      var marker = new google.maps.Marker({
        center: {
          lat: position.coords.latitude,
          lng: position.coords.longitude,
        },
        map: mapHistory,
        title: "Your current location!",
      });
    });
  }

  changeDate(dateid) {
    var tempDate = new Date();

    if (dateid == "today") {
      var td = new Date();
      this.datefrom = new Date(td.setHours(0, 0, 0));
      this.date2 = new Date();
      //console.log('this.datefrom', this.datefrom);
    }
    if (dateid == "yesterday") {
      var yt = moment().subtract(1, "days");
      var ptt = new Date(yt).setHours(0, 0, 0);
      this.datefrom = new Date(ptt);
      var ttt = new Date(yt).setHours(23, 59, 59);
      this.date2 = new Date(ttt);

      //console.log('this.datefrom', this.datefrom);
    }
    if (dateid == "week") {
      var wd = moment().startOf("week");
      this.datefrom = new Date(wd);
      //console.log('this.datefrom', this.datefrom);
      this.date2 = new Date();
    }
    if (dateid == "month") {
      var md = moment().startOf("month").format();
      this.datefrom = new Date(md);
      //console.log('this.datefrom', this.datefrom);
      this.date2 = new Date();
    }
  }
  coloumnClicked = false;

  plotHistory(arrindex) {
    //this._openMapComponet.setHistoryTrack(this._openMapComponet.uniqueIdForHistory,[],[],arrindex,true,'')
  }

  engineCutStatus = "";
  engineCut(device) {
    this.engineCutStatus = device.ignitionLock;

    var identifyType = typeof device.user;
    var userId;
    if (identifyType == "string") {
      userId = device.user;
    } else {
      userId = device.user._id;
    }

    var pload = { uid: userId };
    //console.log(pload);
    this.contactService.checkForPassword(pload).subscribe((res) => {
      //console.log('resres', res);
      var engCutPass = res.engine_cut_psd;
      if (
        engCutPass == undefined ||
        this.superAdmin === true ||
        this.custtype === true
      ) {
        this.immobilizeDevice(device, this.engineCutStatus);
      } else {
        let dialogRef = this.dialog.open(ImmobilizeComponent, {
          data: { engineCutpass: engCutPass },
        });

        dialogRef.afterClosed().subscribe((result) => {
          if (result == "succ") {
            this.immobilizeDevice(device, this.engineCutStatus);
          }
        });
      }
    });
  }

  immobilizeDevice(deviceObj, onOFFcmd) {
    //console.log('deviceObj', deviceObj);
    var deviceCommand = onOFFcmd == "0" ? "OFF" : "ON";
    var devModelId;

    var identifyModelType = typeof deviceObj.device_model;
    var userId;
    if (identifyModelType == "string") {
      devModelId = deviceObj.device_model;
    } else {
      devModelId = deviceObj.device_model._id;
    }

    this.contactService.getDeviceModelbyID(devModelId).subscribe((resModel) => {
      var deviceType = resModel[0].device_type;
      //console.log('resModel', deviceType);
      var cmdqueObj = {
        imei: deviceObj.Device_ID,
        _id: deviceObj._id,
        engine_status: onOFFcmd,
        protocol_type: deviceType,
      };

      this.triggerCmd(cmdqueObj, deviceCommand);
    });

    //console.log("inside immobilize", deviceCommand);
  }

  callLiveTracking = 0;
  triggerCmd(cmdObj, deviceCommand) {
    //console.log("inside triggerCmd function");
    var that = this;
    this.callLiveTracking = 0;
    //  var iurl = '../../assets/image/idle_bus.png';
    // this.Load = true;
    that.errIcon = false;
    that.immobilizeCount = 45;
    that.immobilizeChk = true;
    var timer = setInterval(() => {
      // //console.log("that.immobilizeCount--",that.immobilizeCount--);
      that.immobilizeCount--;
      // //console.log('timer Value',that.immobilizeCount--);
      if (that.immobilizeCount === 0) {
        clearInterval(timer);
      }
    }, 1000);
    this.contactService.addCommandQueue(cmdObj).subscribe((res) => {
      // this.Load = false;
      //console.log(res);
      var cmdQId = res._id;
      //console.log('cmdQId', cmdQId);
      this.intervalTimeOut = setTimeout(function () {
        let message = "Please Try After Sometime";
        // let action
        // that.snackBar.open(message, action, {
        //   duration: 4000,

        // });
        that.errIcon = true;
        that.showErr = true;
        that.ImmErrMsg = message;
        that.shoError = setTimeout(() => {
          that.immobilizeChk = false;
          that.showErr = false;
          clearTimeout(that.shoError);
        }, 5000);
        clearInterval(that.status_cmdq);
        clearTimeout(that.intervalTimeOut);

        clearInterval(timer);
      }, 45000);

      that.status_cmdq = setInterval(function () {
        that.contactService.getEngineCutStatus(cmdQId).subscribe(
          (res) => {
            that.locked = false;
            that.unlocked = false;
            if (res.status == "SUCCESS") {
              that.Load = false;
              var cc = "";
              if (deviceCommand === "ON") {
                cc = "UNLOCKED";
                that.unlocked = true;
              }
              if (deviceCommand === "OFF") {
                cc = "LOCKED";
                that.locked = true;
              }
              let message = "Vehicle" + " " + cc;
              // let action;
              // that.snackBar.open(message, action, {
              //   duration: 4000,
              // });
              that.showErr = true;
              that.ImmErrMsg = message;
              that.shoError = setTimeout(() => {
                that.immobilizeChk = false;
                that.showErr = false;
                clearTimeout(that.shoError);
              }, 5000);
              //console.log("Console after Getting success",that.callLiveTracking);

              if (that.callLiveTracking === 0) {
                that.callLiveTracking = 1;

                that.deviceCQ(cmdObj.imei);
                that.updateLiveTracking(cmdObj.imei, "lockchange");
                // that.refresh();
              }

              clearInterval(timer);
              clearTimeout(that.intervalTimeOut);
              clearInterval(that.status_cmdq);
              // that.immobilizeChk = false;
              // that.Load = false
            }
          },
          (err) => {
            that.errIcon = true;
            let message = "Please Try After Sometime";
            that.showErr = true;
            that.ImmErrMsg = message;
            that.shoError = setTimeout(() => {
              that.immobilizeChk = false;
              that.showErr = false;
              clearTimeout(that.shoError);
            }, 5000);
            let action;
            that.immobilizeChk = false;
            clearInterval(timer);
            // that.snackBar.open(message, action, {
            //   duration: 4000,
            // });
            clearInterval(that.status_cmdq);
            clearTimeout(that.intervalTimeOut);
          }
        );
      }, 3000);
    });
  }

  addressConversion(msg) {
    var outerThis = this;
    var geocoder = new google.maps.Geocoder();
    var latlng = new google.maps.LatLng(msg.latDecimal, msg.longDecimal);

    var request = {
      latLng: latlng,
    };
    // //console.log('latlongVal', request)
    geocoder.geocode(request, function (data, status) {
      if (status == google.maps.GeocoderStatus.OK) {
        if (data[0] != null) {
          outerThis.liveAdd = data[0].formatted_address;
          // //console.log(outerThis.liveAdd);
        } else {
          // //console.log("No address available")
          outerThis.liveAdd = "No address available";
        }
      } else {
        outerThis.liveAdd = "NA";
      }
    });
  }

  armDisarm(deviceObj, action) {
    //console.log('arm disarm');
    var devimei = deviceObj.Device_ID;
    var command = action === "on" ? "ARM" : "DISARM";

    var armDisarmPayload = {
      imei: devimei,
      cmd: command,
    };

    var devModelId_1;
    var identifyModelType = typeof deviceObj.device_model;

    if (identifyModelType == "string") {
      devModelId_1 = deviceObj.device_model;
    } else {
      devModelId_1 = deviceObj.device_model._id;
    }
    this.contactService
      .getDeviceModelbyID(devModelId_1)
      .subscribe((resModel) => {
        var deviceType = resModel[0].device_type;
        armDisarmPayload["protocol_type"] = deviceType;
        this.triggerArmDisarm(armDisarmPayload);
      });
  }

  triggerArmDisarm(ardPayload) {
    this.Load = true;
    this.contactService.armDisarm(ardPayload).subscribe(
      (res) => {
        this.Load = false;

        let message = ardPayload.cmd == "ARM" ? "Activated" : "Deactivated";
        let action;
        this.snackBar.open(message, action, {
          duration: 4000,
        });
        var str = this.currStatus == undefined ? "" : this.currStatus;
        this.getGraphFunction();
        this.getDeviceBYfilter(str, "");
      },
      (err) => {
        this.Load = false;
        //console.log(JSON.parse(err._body));
        let errMsg = err._body
          ? JSON.parse(err._body).message
          : "Plaese Try After Sometime";
        let action;
        this.snackBar.open(errMsg, action, {
          duration: 4000,
        });
      }
    );
  }

  enableMapTrail() {
    this.enabletrail = !this.enabletrail;
    if (this.enabletrail == false) {
      this.flightPathArr = [];
      // this.flightPath_live = new google.maps.Polyline({
      //   path: this.flightPathArr,
      //   geodesic: true,
      //   strokeOpacity: 1.0,
      //   strokeColor: "#0000FF",
      //   strokeWeight: 6
      // });

      this.flightPath_live.setMap(null);
    } else {
      var a = [];
      this.draw_flight_trail(a);
    }
  }
  flightPath_live: any;
  draw_flight_trail(flightPathArr) {
    var tempTimeInterval;
    var that = this;
    if (flightPathArr.length != 0) {
      clearTimeout(tempTimeInterval);
      tempTimeInterval = setTimeout(function () {
        that.flightPath_live = new google.maps.Polyline({
          path: flightPathArr,
          geodesic: true,
          strokeColor: "#0000FF",
          strokeOpacity: 1.0,
          strokeWeight: 6,
        });
        // //console.log(mapData);
        that.flightPath_live.setMap(that.mapNew);
      }, 6000);
    }
  }

  saveAddress(lat, lng, address) {
    var addressObj = {
      lat: lat,
      long: lng,
      address: address,
    };
    this.contactService.saveAdd(addressObj).subscribe(
      (res) => {
        //console.log(res);
      },
      (err) => {
        //console.log("couldn't save address");
      }
    );
  }

  convertDate(utcDate) {
    return moment(utcDate).format("dddd,ll,LTS");
  }
  devIcon: any;
  iconCheck(status, iconType) {
    var devStatus = status.split(" ");
    if (iconType == "car" && devStatus[0] == "OUT") {
      this.devIcon = "../../assets/image/outOfReach_car.png";
      return this.devIcon;
    } else if (iconType == "car" && devStatus[0] == "RUNNING") {
      this.devIcon = "../../assets/image/running_car.png";
      return this.devIcon;
    } else if (iconType == "car" && devStatus[0] == "STOPPED") {
      this.devIcon = "../../assets/image/stopped_car.png";
      return this.devIcon;
    } else if (iconType == "car" && devStatus[0] == "IDLING") {
      this.devIcon = "../../assets/image/idle_car.png";
      return this.devIcon;
    } else if (iconType == "car" && devStatus[0] == "NO") {
      this.devIcon = "../../assets/image/no_data.png";
      return this.devIcon;
    } else if (iconType == "bike" && devStatus[0] == "OUT") {
      this.devIcon = "../../assets/image/outOfReach_bike.png";
      return this.devIcon;
    } else if (iconType == "bike" && devStatus[0] == "RUNNING") {
      this.devIcon = "../../assets/image/running_bike.png";
      return this.devIcon;
    } else if (iconType == "bike" && devStatus[0] == "STOPPED") {
      this.devIcon = "../../assets/image/stopped_bike.png";
      return this.devIcon;
    } else if (iconType == "bike" && devStatus[0] == "IDLING") {
      this.devIcon = "../../assets/image/idle_bike.png";
      return this.devIcon;
      // }
    } else if (iconType == "bike" && devStatus[0] == "NO") {
      this.devIcon = "../../assets/image/no_data.png";
      return this.devIcon;
    } else if (iconType == "bus" && devStatus[0] == "OUT") {
      this.devIcon = "../../assets/image/bus_out.png";
      return this.devIcon;
    } else if (iconType == "bus" && devStatus[0] == "RUNNING") {
      this.devIcon = "../../assets/image/bus_running.png";
      return this.devIcon;
    } else if (iconType == "bus" && devStatus[0] == "STOPPED") {
      this.devIcon = "../../assets/image/bus_stop.png";
      return this.devIcon;
    } else if (iconType == "bus" && devStatus[0] == "IDLING") {
      this.devIcon = "../../assets/image/idle_bus.png";
      return this.devIcon;
    } else if (iconType == "bus" && devStatus[0] == "NO") {
      this.devIcon = "../../assets/image/no_data.png";
      return this.devIcon;
    } else if (iconType == "truck" && devStatus[0] == "OUT") {
      this.devIcon = "../../assets/image/our_truck.png";
      return this.devIcon;
    } else if (iconType == "truck" && devStatus[0] == "RUNNING") {
      this.devIcon = "../../assets/image/running_truck.png";
      return this.devIcon;
    } else if (iconType == "truck" && devStatus[0] == "STOPPED") {
      this.devIcon = "../../assets/image/stopped_truck.png";
      return this.devIcon;
    } else if (iconType == "truck" && devStatus[0] == "IDLING") {
      this.devIcon = "../../assets/image/idle_truck.png";
      return this.devIcon;
    } else if (iconType == "truck" && devStatus[0] == "NO") {
      this.devIcon = "../../assets/image/no_data.png";
      return this.devIcon;
    } else if (iconType == "tractor" && devStatus[0] == "OUT") {
      this.devIcon = "../../assets/image/tractor_blue.png";
      return this.devIcon;
    } else if (iconType == "tractor" && devStatus[0] == "RUNNING") {
      this.devIcon = "../../assets/image/tractor_green.png";
      return this.devIcon;
    } else if (iconType == "tractor" && devStatus[0] == "STOPPED") {
      this.devIcon = "../../assets/image/tractor_red.png";
      return this.devIcon;
    } else if (iconType == "tractor" && devStatus[0] == "IDLING") {
      this.devIcon = "../../assets/image/tractor_yellow.png";
      return this.devIcon;
    } else if (iconType == "ambulance" && devStatus[0] == "OUT") {
      this.devIcon = "../../assets/images/liveTrackIcons/ambulance_b.png";
      return this.devIcon;
    } else if (iconType == "ambulance" && devStatus[0] == "RUNNING") {
      this.devIcon = "../../assets/images/liveTrackIcons/ambulance_g.png";
      return this.devIcon;
    } else if (iconType == "ambulance" && devStatus[0] == "STOPPED") {
      this.devIcon = "../../assets/images/liveTrackIcons/ambulance_r.png";
      return this.devIcon;
    } else if (iconType == "ambulance" && devStatus[0] == "IDLING") {
      this.devIcon = "../../assets/images/liveTrackIcons/ambulance_y.png";
      return this.devIcon;
    } else if (iconType == "tractor" && devStatus[0] == "NO") {
      this.devIcon = "../../assets/image/no_data.png";
      return this.devIcon;
    } else if (!iconType && devStatus[0] == "OUT") {
      this.devIcon = "../../assets/image/outOfReach_car.png";
      return this.devIcon;
    } else if (!iconType && devStatus[0] == "RUNNING") {
      this.devIcon = "../../assets/image/running_car.png";
      return this.devIcon;
    } else if (!iconType && devStatus[0] == "STOPPED") {
      this.devIcon = "../../assets/image/stopped_car.png";
      return this.devIcon;
    } else if (!iconType && devStatus[0] == "IDLING") {
      this.devIcon = "../../assets/image/idle_car.png";
      return this.devIcon;
    } else if (!iconType && devStatus[0] == "NO") {
      this.devIcon = "../../assets/image/no_data.png";
      return this.devIcon;
    } else if (iconType == "user" && devStatus[0] == "OUT") {
      this.devIcon = "../../assets/image/user_b.png";
      return this.devIcon;
    } else if (iconType == "user" && devStatus[0] == "RUNNING") {
      this.devIcon = "../../assets/image/user_g.png";
      return this.devIcon;
    } else if (iconType == "user" && devStatus[0] == "STOPPED") {
      this.devIcon = "../../assets/image/user_r.png";
      return this.devIcon;
    } else if (iconType == "user" && devStatus[0] == "IDLING") {
      this.devIcon = "../../assets/image/user_y.png";
      return this.devIcon;
    } else if (iconType == "user" && devStatus[0] == "NO") {
      this.devIcon = "../../assets/image/no_data.png";
      return this.devIcon;
    } else if (iconType == "jcb" && devStatus[0] == "OUT") {
      this.devIcon = "../../assets/image/jcb_blue.png";
      return this.devIcon;
    } else if (iconType == "jcb" && devStatus[0] == "RUNNING") {
      this.devIcon = "../../assets/image/jcb_green.png";
      return this.devIcon;
    } else if (iconType == "jcb" && devStatus[0] == "STOPPED") {
      this.devIcon = "../../assets/image/jcb_red.png";
      return this.devIcon;
    } else if (iconType == "jcb" && devStatus[0] == "IDLING") {
      this.devIcon = "../../assets/image/jcb_yellow.png";
      return this.devIcon;
    } else if (iconType == "jcb" && devStatus[0] == "NO") {
      this.devIcon = "../../assets/image/no_data.png";
      return this.devIcon;
    } else {
      this.devIcon = "../../assets/image/noIcon.png";
      return this.devIcon;
    }
  }

  locationShare(device) {
    let dialogRef = this.dialog.open(ShareLocComponent, {
      width: "500px",
      data: { deviceObject: device },
    });

    dialogRef.afterClosed().subscribe((result) => {
      if (result == "succ") {
        this.data_descip = "Location Shared";
        // this.immobilizeDevice(device, this.engineCutStatus);
      }
      function launch_toast() {
        // //console.log(divid);
        var x = document.getElementById("toast");
        ////console.log(x);
        x.className = "show";
        setTimeout(function () {
          x.className = x.className.replace("show", "");
        }, 1500);
      }
    });
  }

  getAddress(lat, lng) {
    var latlng_1 = {
      lat: lat,
      long: lng,
    };
    this.contactService.getAddressByApi(latlng_1).subscribe((res) => {
      if (res.address != undefined) {
        this.historyAdress = res.address;
      }
    });
  }

  getSystemLogs(imeiObj) {
    var tDate = new Date();
    tDate.setSeconds(0);
    tDate.setMilliseconds(0);
    var fDate = new Date().setHours(0, 0, 0, 0);
    var payLoad = {
      draw: 5,
      columns: [
        {
          data: "_id",
        },
        {
          data: "imei",
        },
        {
          data: "date",
        },
        {
          data: "latDecimal",
        },
        {
          data: "longDecimal",
        },
        {
          data: "insertionTime",
        },
        {
          data: "syncedAt",
        },
        {
          data: "integrationResponse",
        },
        {
          data: "speed",
        },
        {
          data: "ac",
        },
        {
          data: "currentFuel",
        },
        {
          data: "raw",
        },
        {
          data: "ignition",
        },
        {
          data: "power",
        },
        {
          data: "fuelVoltage",
        },
        {
          data: "rawio",
        },
        {
          data: "external_Battery",
        },
        {
          data: "powerCutAlarm",
        },
        {
          data: "satellites",
        },
      ],
      order: [
        {
          column: 4,
          dir: "asc",
        },
      ],
      start: 0,
      length: 100,
      search: {
        value: "",
        regex: false,
      },
      op: {},
      select: [],
      find: {
        imei: imeiObj.Device_ID,
        insertionTime: {
          $gte: {
            _eval: "date",
            value: new Date(fDate).toISOString(),
          },
          $lte: {
            _eval: "date",
            value: tDate.toISOString(),
          },
        },
      },
    };
    var suburl = "/gps/datatable";

    this.contactService.post(suburl, payLoad).subscribe(
      (resp) => {
        //console.log(resp);
        var tempLog = resp;
        this.gpsDataArr = [];
        this.gpsDataArr = resp["data"];
        for (var i = 0; i < this.gpsDataArr.length; i++) {
          if (typeof this.gpsDataArr[i].integrationResponse == "object") {
            this.gpsDataArr[i].integrationResponse = JSON.stringify(
              this.gpsDataArr[i].integrationResponse
            );
          }
        }
        //console.log('this.gpsDataArr',this.gpsDataArr);
      },
      (err) => {}
    );
  }
  dcqData = [];
  deviceCQ(imeiObj) {
    var imei = imeiObj.Device_ID ? imeiObj.Device_ID : imeiObj;
    this.dcqData = [];
    this.contactService.deviceCmdQueue(imei).subscribe(
      (resp) => {
        var tempLog = resp;
        this.dcqData = resp;
      },
      (err) => {
        this.dcqData = [];
      }
    );
  }

  historySeekbaar() {}

  changeSpeed(t) {
    //console.log(t);
    this.speed = t * 100;
    var header = document.getElementById("myDIV");
    var btns = header.getElementsByClassName("sc-bdVaJa");
    for (var i = 0; i < btns.length; i++) {
      btns[i].addEventListener("click", function () {
        var current = document.getElementsByClassName("active");
        current[0].className = current[0].className.replace(" active", "");
        this.className += " active";
      });
    }
  }

  nearByValue: number = 1000;
  changeRangeNearby() {
    var rangeVal1 = document.getElementById("nearbySlider");
    this.nearByValue = rangeVal1["value"];
  }

  getNearByVehicles(devData) {
    //console.log(devData);
    var payLoad = {
      uid: this.useridd,
      distance: this.nearByValue,
      coord: { lat: devData.latDecimal, long: devData.longDecimal },
    };
    this.contactService.getNearByVehicles(payLoad).subscribe((res) => {
      //console.log(res);
      this.deviceList = [];
      this.deviceList = res;
      if (this.deviceList.length != 0) {
        if (this.deviceList.length === 0) {
          this.lastcall = false;
          this.firstcall = true;
        }
        this.foods = [];
        for (var k = 0; k < this.deviceList.length; k++) {
          this.deviceList[k]["playPause"] = true;
          this.deviceList[k]["checked"] = true;
          if (this.deviceList[k].type_of_device == "Tracker") {
            let a = {
              value: this.deviceList[k].Device_Name,
              viewValue: this.deviceList[k].Device_Name,
              did: this.deviceList[k].Device_ID,
              id: this.deviceList[k]._id,
              user: this.deviceList[k].user,
              email: this.deviceList[k].Email_ID,
              deviceType: this.deviceList[k].type_of_device,
              iconType: this.deviceList[k].iconType,
              //      checked:true
            };
            this.foods.push(a);
            if (k === this.deviceList.length - 1) {
              console.log("1111111121212");
              this.livetrack(null);
            }
          }
        }
        console.log("this.deviceList", this.deviceList);
      } else {
        this.data_descip = "No Nearby Devices Found !!!";
        launch_toast();
      }

      function launch_toast() {
        // //console.log(divid);
        var x = document.getElementById("toast");
        ////console.log(x);
        x.className = "show";
        setTimeout(function () {
          x.className = x.className.replace("show", "");
        }, 1500);
      }
    });
  }

  directionShow(deviceObj) {
    var lat = deviceObj.last_location.lat;
    var long = deviceObj.last_location.long;

    var url =
      "https://www.google.com/maps/dir/?api=1&destination=" +
      lat +
      "," +
      long +
      "&travelmode=driving";
    window.open(url, "_blank");
  }

  getStringifyio(rawio) {
    //console.log('askdjsahdiasjdasdlkasdjasdlkadjajldadadaa',rawio);
    return JSON.stringify(rawio);
  }

  viewStreet() {
    //console.log("Street View");
  }

  triggerDeviceCmd(dev) {
    //console.log('device Object',dev);
    //  CmdUIComponent
    let dialogRef = this.dialog.open(CommandWindowComponent, {
      width: "500px",
      data: { deviceObject: dev },
    });

    dialogRef.afterClosed().subscribe((result) => {
      if (result == "succ") {
        this.data_descip = "Command Successfully Triggered";
        launch_toast();
      }

      if (result == "openOther") {
        let dialogRef_1 = this.dialog.open(CmdUIComponent, {
          width: "500px",
          data: { deviceObject: dev },
        });
        dialogRef_1.afterClosed().subscribe((result) => {
          if (result === "cancel") {
            //console.log('Working Fine');
          }

          if (result === "succ") {
            this.data_descip = "Command Triggered Successfully";
            launch_toast();
          }
        });
      }
      function launch_toast() {
        var x = document.getElementById("toast");
        x.className = "show";
        setTimeout(function () {
          x.className = x.className.replace("show", "");
        }, 1500);
      }
    });
  }
  parkingArr = [];

  parkingData(fTime, tTime, uid, dev) {
    console.log("fTime, tTime,uid,dev", fTime, tTime, uid, dev);
    var fd = new Date(fTime);
    var td = new Date(tTime);
    var userid = dev.user._id != undefined ? dev.user._id : dev.user;
    var device_imei = dev._id;

    this.contactService
      .stoppage_report(fd.toISOString(), td.toISOString(), userid, device_imei)
      .subscribe(
        (res) => {
          this.parkingArr = [];
          this.parkingArr = res;

          console.log("response=>", res);
        },
        (err) => {
          this.parkingArr = [];
        }
      );
  }

  notifArray = [];
  bulkVar: any;
  notificationData(fTime, tTime, uid, dev) {
    //console.log('fTime, tTime,uid,dev',fTime, tTime,uid,dev);

    var fd = new Date(fTime);
    var td = new Date(tTime);
    var userid = dev.user._id != undefined ? dev.user._id : dev.user;
    // var userid:any;
    //console.log(dev);
    var device_imei = dev.Device_ID;

    var skip = 1;
    var limit = 200;

    this.contactService
      .filteredNotifications(
        fd,
        td,
        this.bulkVar,
        device_imei,
        userid,
        skip,
        limit
      )
      .subscribe(
        (res) => {
          //console.log('res=>',res);
          this.notifArray = [];
          this.notifArray = res;
        },
        (err) => {
          this.notifArray = [];
        }
      );
  }

  getDuration(atime, dtime) {
    let arrival_time = new Date(atime).toLocaleString();
    let departure_time = new Date(dtime).toLocaleString();
    var fd = new Date(arrival_time).getTime();
    var td = new Date(departure_time).getTime();
    var time_difference = td - fd;
    var total_min = time_difference / 60000;
    var hours = total_min / 60;
    var rhours = Math.floor(hours);
    var minutes = (hours - rhours) * 60;
    var rminutes = Math.round(minutes);
    let Durations = rhours + " " + "hrs" + " " + rminutes + "min";
    return Durations;
  }

  getAlink(lat, lng) {
    //  lat +","+lng +
    //  https://maps.google.com/?q=

    var addressLink = "https://maps.google.com/?q=" + lat + "," + lng;
    return addressLink;
  }

  liveEventsData: any = [];
  nType: any;
  getRecentNotification(colObj) {
    var fd = new Date();
    fd.setHours(0, 0, 0, 0);
    var fromD = new Date(fd);
    var td = new Date();
    // var user =  colObj.user;
    var user = colObj.user._id != undefined ? colObj.user._id : colObj.user;
    var did = colObj.Device_ID;

    //console.log('Inside get Notification Function',this.deviceSelect);
    var skip = 1;
    var limit = 200;

    this.contactService
      .filteredNotifications(fromD, td, this.nType, did, user, skip, limit)
      .subscribe(
        (res) => {
          //console.log('Inside get Notification Function',did);
          this.liveEventsData = [];
          this.liveEventsData = res;
          this.socket_Notify.on(this.useridd, this.accListener());
        },
        (err) => {
          this.liveEventsData = [];
        }
      );
  }

  accListener() {
    //console.log('this is accListner');
    var outerThis = this;
    return function (msg) {
      //console.log('message=>',msg);

      if (
        this.deviceSelect &&
        this.deviceSelect.length &&
        msg.device == this.deviceSelect[0].Device_ID
      ) {
        // this.liveEventsData.push(msg);
        this.liveEventsData.splice(0, 0, msg);
      }

      //console.log('accListner=>',this.liveEventsData)
    };
  }

  addVehicle() {
    var that = this;
    let dialogRef = this.dialog.open(AddDeviceComponent, {
      width: "800px",
    });

    dialogRef.afterClosed().subscribe((result) => {
      if (result == "added") {
        // that.refresh();
        that.tost1("added");
      }
    });
  }
  checkBoxValue1(event) {
    this.satelliteDisabled = event.checked;
  }

  checkBoxValue(ev, i, device: any = {}) {
    if (device.Device_ID) {
      device.checked = ev.checked;
    } else {
      var indexSwitch = this.markerArray[i] === undefined ? 0 : i;
      if (ev.checked === false) {
        this.markerArray[indexSwitch].marker.setMap(null);
      }

      var that = this;
      this.deviceList.filter((dl, index) => {
        if (dl.Device_ID == this.markerArray[indexSwitch].imei) {
          that.deviceList[index].checked = ev.checked;
        }
      });
    }
    if (this.deviceList.length == 1 && this.deviceList[0].checked) {
      // this.updateLiveTracking(this.deviceList[0],null);
    }
    this._openMapComponet.setMasterDeviceList(this.deviceList);
  }
  updateLiveTracking(device, ev) {
    this.deviceList.forEach((dData) => {
      dData.checked = false;
    });
    device.checked = true;
    this.deviceName = device.Device_Name;
    this.deviceSelect = [device];
    this._openMapComponet.setMasterDeviceList(this.deviceList);
    this.getAddressBy({}, device, true);
  }

  selectGroup(event, item) {
    var index = [];

    if (event.checked) {
      this.deviceList
        .filter(
          (x) =>
            x.vehicleGroup == undefined || x.vehicleGroup.name !== item.name
        )
        .forEach(
          (x) => (this.deviceList[this.deviceList.indexOf(x)].checked = false)
        );
      this.deviceList.filter((x) => {
        if (x.vehicleGroup) {
          if (x.vehicleGroup.name === item.name) {
            var ev = { checked: true };
            this.checkBoxValue(ev, this.deviceList.indexOf(x));
          }
        } else {
          var ev = { checked: false };
          this.checkBoxValue(ev, this.deviceList.indexOf(x));
        }
      });
    } else {
      this.deviceList.forEach((x) => {
        x.checked = true;
        var ev = { checked: true };
        this.checkBoxValue(ev, this.deviceList.indexOf(x));
      });
    }

    // for(var i=0;i<this.deviceList.length;i++){
    //   if(de)
    //   var ev={checked:true}
    //   this.checkBoxValue(ev,index[i]);
    // }

    // }).forEach(x =>
    // console.log(x)
    // );
  }

  getUserDetails() {
    this.contactService.getUserObj(this.useridd).subscribe((res: any) => {
      // console.log("RESPONSE",res);
      if (res.label_setting !== undefined) {
        this.showLabels = res.label_setting;
        this.digitalInput = res.digital_input;
      }
      if (res.user_settings) {
        if (res.user_settings.sateliteValue)
          this.satelite = res.user_settings.sateliteValue;
      }
    });
  }

  // @HostListener('click', ['$event'])
  // onClick(event) {
  //   if (event.target.id === 'deletePoint'){
  //     console.log(event.target.value);
  //     this.latlongObjArr.splice(event.target.value,1);
  //     this.maphistory(1)
  //   }

  // }
  // CLICK(data){
  //   console.log(data);

  // }

  // ------------new Method for calculate area------------------
  cordinates = [];
  showArea() {
    var imei = JSON.parse(localStorage.getItem("devDetail"))
      ? JSON.parse(localStorage.getItem("devDetail"))
      : this.temptrackingDev;

    if (!imei) {
      imei = this.deviceSelect[0].did
        ? this.deviceSelect[0].did
        : this.deviceSelect[0].Device_ID;
    } else {
      if (imei.vehicleId) {
        imei = imei.vehicleId;
      } else {
        imei = imei;
      }
    }

    var data = {
      f: new Date(this.datefrom).toISOString(),
      t: new Date(this.date2).toISOString(),
      imei: imei,
    };

    this.contactService.calculateArea(data).subscribe((res: any) => {
      if (res.area) this.area = (res.area / 1000000) * 247;

      // let a = res.pts;
      //     for(let k=0;k<a.length;k++){
      //     let b ={
      //     lat : a[k]['latitude'],
      //     lng : a[k]['longitude']
      //     }
      //     this.cordinates.push(b);
      //     }

      //     console.log(this.cordinates);
      //     // this.draw1(this.cordinates,'')
    });
  }

  change(device) {
    if (device) {
      this.deviceSelect[0] = device;
      let fDevice = this._openMapComponet.masterDevicesList.find(
        (d) => d.Device_ID == device.Device_ID
      );
      if (fDevice) {
        this.deviceSelect[0] = fDevice;
        this.updateLiveTracking(fDevice, null);
      }
    }
  }
  startAddress: any;
  deviceNameForPDF;
  startTime;
  endTime;
  endAddress: any;
  pdfFunction(data) {}
  getAddressForPDF(lat, lng, type) {
    var outerThis = this;

    let geocoder = new google.maps.Geocoder();

    let request = {
      latLng: new google.maps.LatLng(lat, lng),
    };
    geocoder.geocode(request, function (data, status) {
      if (status == google.maps.GeocoderStatus.OK) {
        if (data[0] != null) {
          // var liveAdd = ;

          if (type == "start") {
            outerThis.startAddress = data[0].formatted_address;
          } else {
            outerThis.endAddress = data[0].formatted_address;
          }
          return data[0].formatted_address;
        }
      } else {
        //  console.log(liveAdd);
        return "N/A";
      }
    });
  }

  image;
  pdf() {
    debugger;
    this.getTravelPathReport(this.deviceSelect[0]).then((resp12) => {
      var image = "";
      if ((this.deviceList[0].supAdmin.imageDoc || []).length != 0) {
        var str = this.deviceList[0].supAdmin.imageDoc[0];
        var splitStr = str.split("/");
        var concatStr = "";
        for (var i = 1; i < splitStr.length; i++) {
          if (i > 0) {
            var tt = splitStr[i];
            concatStr += "/" + tt;
          }
        }
        image = "https://www.oneqlik.in" + concatStr;
      }
      this.deviceNameForPDF =
        this._openMapComponet.activeHistoryTrack.currentPath.device_name;
      this.startTime =
        this._openMapComponet.activeHistoryTrack.currentPath.fromTime;
      this.endTime =
        this._openMapComponet.activeHistoryTrack.currentPath.toTime;
      var name =
        this.deviceNameForPDF +
        " track from " +
        this.startTime +
        " to " +
        this.endTime +
        ".pdf";
      var outerThis = this;
      this.startAddress = this.finalArr[0].address;
      this.endAddress = this.finalArr[this.finalArr.length - 1].address;

      var element = $("#newmap1");
      var pdfOptions = {
        orientation: "landscape", // One of "portrait" or "landscape" (or shortcuts "p" (Default), "l")
        unit: "mm", //Measurement unit to be used when coordinates are specified. One of "pt" (points), "mm" (Default), "cm", "in"
        format: "legal", //One of 'a3', 'a4' (Default),'a5' ,'letter' ,'legal'
      };

      var doc = new jsPDF(pdfOptions);

      var pageWidth = doc.internal.pageSize.width - 20;
      var width = pageWidth;

      html2canvas(element, {
        useCORS: true, // MUST
        onrendered: function (canvas) {
          var imgWidth = element.width();
          var imgHeight = element.height();

          var height = (pageWidth * imgHeight) / imgWidth;
          var imgData = canvas.toDataURL("image/png");
          doc.addImage(imgData, "PNG", 5, 30, width, height);
          outerThis.toDataURL(image, function (dataUrl) {
            if (image) doc.addImage(dataUrl, "JPEG", 2, 2, 27, 27);
            let finalY = doc.previousAutoTable.finalY;
            var header = function (data) {
              doc.setFontSize(15);
              doc.setTextColor(40);
              doc.setFontStyle("normal");
            };
            doc.autoTable({
              html: "#headerTable",
              margin: { bottom: 140, left: 30, right: 8, top: 2 },
              theme: "plain",
            });

            //  var options = {
            //     beforePageContent: header,
            //   //   margin: {
            //   //     top: 300
            //   //   },
            //   //   // startY:doc.lastAutoTable+ 300
            //   //  startY: 300
            //     // startY: doc.autoTableEndPosY() + 300
            // };
            doc.autoTable({
              head: outerThis.headRows(),
              // margin: { top: 80 },
              startY: doc.autoTable.previous.finalY + 200,
              body: outerThis.bodyRows(
                outerThis.finalArr.length,
                outerThis.finalArr
              ),
              // beforePageContent: header,
            });
            doc.save(name);
          });
        },
      });
    });
  }

  toDataURL(url, callback) {
    var xhr = new XMLHttpRequest();
    xhr.onload = function () {
      var reader = new FileReader();
      reader.onloadend = function () {
        callback(reader.result);
      };
      reader.readAsDataURL(xhr.response);
    };
    xhr.open("GET", url);
    xhr.responseType = "blob";
    xhr.send();
  }

  selectedGroup(event) {
    console.log(event, this.toppings);
    this.getDeviceBYfilter("", "");
  }

  getGrp() {
    this.contactService.getGroup(this.useridd).subscribe((res) => {
      this.groups = res["group_details"];
    });
  }

  selectAllVehicles(ev) {
    // console.log(ev);
    if (ev.checked) {
      this.deviceObj = [];
      var Alldevices = {
        id: "all",
        viewValue: "ALL Devices",
        iconType: "",
        deviceId: "",
      };
      if (this.deviceList.length == 1) {
        this.selectedDevice = this.deviceList[0]._id;
        this.parkingButtonShow =
          this.deviceList[0].theftAlert == null
            ? "grey"
            : this.deviceList[0].theftAlert == undefined
            ? "grey"
            : this.deviceList[0].theftAlert == true
            ? "green"
            : "red";
        this.DriverName = this.deviceList[0].driver_name;
        // console.log("DRIVER NAME",this.DriverName,this.deviceList[0].ac);
        this.ac = this.deviceList[0].ac ? this.deviceList[0].ac : "NA";
        this.DriverNumber = this.deviceList[0].contact_number;
      }
      // //console.log("device obj =>",this.deviceList);
      this.deviceObj.push(Alldevices);
      for (var i = 0; i < this.deviceList.length; i++) {
        Alldevices = {
          id: this.deviceList[i]._id,
          viewValue: this.deviceList[i].Device_Name
            ? this.deviceList[i].Device_Name
            : "",
          iconType: this.deviceList[i].iconType,
          deviceId: this.deviceList[i].Device_ID,
        };
        this.deviceObj.push(Alldevices);
      }

      this.final = this.deviceList;

      for (let i = 0; i < this.final.length; i++) {
        this.final[i]["checked"] = true;
        // this.deviceList = this.final;

        if (this.final[i].type_of_device == "Tracker") {
          let a = {
            value: this.final[i].Device_Name,
            viewValue: this.final[i].Device_Name,
            did: this.final[i].Device_ID,
            id: this.final[i]._id,
            user: this.final[i].user,
            email: this.final[i].Email_ID,
            deviceType: this.final[i].type_of_device,
            iconType: this.final[i].iconType,
          };

          this.foods.push(a);
        }
      }
      let that = this;
      if (this.navId === undefined || this.navId != "locationHistory") {
        this.livetrack(this.fin);
      }

      for (let y = 0; y < this.foods.length; y++) {
        if (this.foods[y].did == this.fin) {
          this.new = this.foods[y];
        }
      }
      this.masterFoods = this.foods;
    } else {
      this.deviceList.forEach((element) => {
        element.checked = false;
      });
      const myOptions = {
        zoom: 2,
        center: new google.maps.LatLng(18.602941, 73.777147),
        mapTypeId: google.maps.MapTypeId.ROADMAP,
      };
    }
    this._openMapComponet.setMasterDeviceList(this.deviceList);
  }
  reportArr;
  finalArr = [];
  reportArr1;
  pathReport = [];
  getTravelPathReport(device) {
    return new Promise((a, b) => {
      var payload = {
        to: new Date(this.date2).toISOString(),
        from: new Date(this.datefrom).toISOString(),
        device: device.Device_ID ? device.Device_ID : device.did,
        interval: 10,
      };

      this.contactService.getTravel_path_report(payload).subscribe(
        (resp: any) => {
          this.reportArr = [];
          if (resp && resp.length) {
            this.reportArr = resp.filter(function (el) {
              return el != null;
            });
          }

          let last = { speed: "" };
          let result = [];

          for (let i = 0; i < this.reportArr.length; i++) {
            var cum_distance =
              parseFloat(this.reportArr[i].odo) -
              parseFloat(this.reportArr[0].odo);
            this.reportArr[i].cum_distance = Math.abs(
              parseFloat(cum_distance.toFixed(2))
            );

            // let char = this.reportArr[i];
            // if(char.speed !== last.speed){
            //   result.push(char);
            //   last = char;
            // }
          }
          // console.log("RESSSS==>",this.reportArr);
          this.reportArr1 = this.reportArr;
          let latLongArray: any[] = [];
          this.reportArr1.forEach((deData) => {
            latLongArray.push({
              long: deData.longDecimal ? deData.longDecimal : 0,
              lat: deData.latDecimal ? deData.latDecimal : 0,
            });
          });

          this.contactService
            .getAddressByApiBulk(latLongArray)
            .subscribe((latLongAddress) => {
              if (latLongAddress && latLongAddress.length) {
                this.reportArr1.forEach((deData, index) => {
                  let latLng = {
                    lat: deData.latDecimal ? deData.latDecimal : 0,
                    long: deData.longDecimal ? deData.longDecimal : 0,
                  };
                  this.contactService.latLongAddress[
                    latLng.long + "_" + latLng.lat
                  ] = latLongAddress[index];
                });
              }

              if (this.reportArr1.length != 0) {
                var j = 0;
                // console.log(this.reportArr1);
                for (let i = 0; i < resp.length; i++) {
                  if (resp[i] != null) {
                    resp[i].Device_name = device.Device_Name;
                    this.pathReport.push(resp[i]);
                  } else {
                  }
                }

                this.finalArr = [];
                var that = this;
                // console.log(this.finalArr);
                for (var i = 0; i < this.reportArr1.length; i++) {
                  this.clocation_1(this.reportArr1[i], function (err, succ) {
                    if (err) {
                      // console.log(err);
                      j++;
                    } else {
                      // console.log(succ);
                      succ["index"] = j;
                      that.finalArr.push(succ);
                      // if(j==0){
                      //   that.startAddress=succ.address
                      // }
                      // console.log(that.finalArr,j);
                      j++;
                      if (j === that.reportArr1.length) {
                        // that.endAddress=succ.address
                        that.Load = false;
                        that.finalArr.sort(function (a: any, b: any) {
                          return (
                            new Date(a.date).valueOf() -
                            new Date(b.date).valueOf()
                          );
                        });
                        // callback({ data: this.finalArr });
                      }
                    }
                  });
                }
                if (this.pathReport.length == 0) {
                  this.Load = false;
                }
              } else {
                this.Load = false;
                this.firstcall = true;
                this.lastcall = this.skip > 0 ? false : true;
              }
              a(new Date().getTime());
            });
        },
        (err) => {
          this.Load = false;
          b(new Date().getTime());
          // console.log("error",err) ;
        }
      );
    });
  }

  clocation_1(latlngObj, cb) {
    if (latlngObj == null) {
      cb(null, latlngObj);
    }
    var outerThis = this;
    var la = "";

    let latLng = {
      lat: "0",
      long: "0",
    };

    latLng = {
      lat: latlngObj.latDecimal ? latlngObj.latDecimal : 0,
      long: latlngObj.longDecimal ? latlngObj.longDecimal : 0,
    };

    // if () {
    //   latLng = {
    //     lat: 0,
    //     long: 0
    //   }
    // }

    outerThis.contactService.getAddressByApi(latLng).subscribe((res) => {
      if (res.message == "Address not found in databse") {
        var adata = {
          iden: "noaddress",
          latlng: latLng,
        };
        latlngObj["address"] = adata;
        // cb(null,latlngObj);
        var latLng_1 = {
          lat: "0",
          long: "0",
        };

        latLng_1 = {
          lat: latlngObj.latDecimal ? latlngObj.latDecimal : 0,
          long: latlngObj.longDecimal ? latlngObj.longDecimal : 0,
        };

        outerThis.contactService.getAddressByApi(latLng_1).subscribe((res) => {
          if (res.message == "Address not found in databse") {
            var bdata = {
              iden: "noaddress",
              latlng: latLng_1,
            };

            latlngObj["address"] = bdata;
            cb(null, latlngObj);
          } else {
            latlngObj["address"] = res.address;
            cb(null, latlngObj);
          }
        });
      } else {
        latlngObj["address"] = res.address;
        var latLng_1 = {
          lat: "0",
          long: "0",
        };

        latLng_1 = {
          lat: latlngObj.latDecimal ? latlngObj.latDecimal : 0,
          long: latlngObj.longDecimal ? latlngObj.longDecimal : 0,
        };

        outerThis.contactService.getAddressByApi(latLng_1).subscribe((res) => {
          if (res.message == "Address not found in databse") {
            var cdata = {
              iden: "noaddress",
              latlng: latLng_1,
            };

            latlngObj["address"] = cdata;
            cb(null, latlngObj);
          } else {
            latlngObj["address"] = res.address;
            cb(null, latlngObj);
          }
        });

        // cb(null,latlngObj);
      }
    });
  }

  headRows() {
    return [
      // displayedColumns=['vehicleName','IMEI','totalDistance','fuel','ignOn','ignOff','idleTime','outOfReach','noGps','trips','maxSpeed','startLocation','endLocation','details'];

      {
        deviceName: "device Name",
        imei: "IMEI",
        date: "Date",
        odo: "ODO",
        distanceFromPrevious: "Distance",
        speed: "Speed",
        avgSpeed: "AVG Speed",
        externalBattery: "Ext Battery",
        temperature: "Temperature",
        cumDistance: "Cum Distance",
        location: "Location",
        address: "Address",
      },
    ];
  }

  bodyRows(rowCount, pdfBody) {
    rowCount = rowCount || 10;
    let body = [];

    for (var j = 0; j < rowCount; j++) {
      var str =
        (pdfBody[j].latDecimal ? pdfBody[j].latDecimal : 0) +
        " , " +
        (pdfBody[j].longDecimal ? pdfBody[j].longDecimal : 0);
      body.push({
        deviceName: pdfBody[j].Device_name,
        imei: pdfBody[j].imei,
        date: moment(pdfBody[j].date).format("lll"),
        odo: pdfBody[j].odo ? pdfBody[j].odo.toFixed(2) : 0,
        distanceFromPrevious: this.get_distance(pdfBody[j], pdfBody[j].index),
        speed: pdfBody[j].speed,
        avgSpeed: this.getavgSpeed(pdfBody[j], pdfBody[j].index),
        externalBattery: pdfBody[j].external_Battery
          ? pdfBody[j].external_Battery
          : "0",
        temperature: pdfBody[j].temp
          ? (parseFloat(pdfBody[j].temp) / 10).toFixed(2)
          : "0",
        cumDistance: this.getcummulative_distance(pdfBody[j], pdfBody[j].index),
        location: str,
        address: pdfBody[j].address,
      });
    }
    return body;
  }

  getcummulative_distance(gps_report, index) {
    if (index == 0) {
      return 0.0;
    } else {
      var cum_distance =
        parseFloat(this.reportArr1[index].odo) -
        parseFloat(this.reportArr1[0].odo);
      return Math.abs(parseFloat(cum_distance.toFixed(2)));
    }
  }

  getavgSpeed(gps_report, index_1) {
    if (index_1 == 0) {
      return 0.0;
    } else {
      var cum_distance =
        parseFloat(this.reportArr1[index_1].odo) -
        parseFloat(this.reportArr1[index_1 - 1].odo);
      return Math.abs(parseFloat((cum_distance / 0.166).toFixed(2)));
    }
  }

  get_distance(gps_report, index_1) {
    if (index_1 == 0) {
      return 0.0;
    } else {
      var cum_distance =
        parseFloat(this.reportArr1[index_1].odo) -
        parseFloat(this.reportArr1[index_1 - 1].odo);
      return Math.abs(parseFloat(cum_distance.toFixed(2)));
    }
  }

  changeParking() {
    var theftAlert =
      this.parkingButtonShow == "grey"
        ? true
        : this.parkingButtonShow == "green"
        ? false
        : true;
    this.contactService
      .post("/devices/deviceupdate", {
        _id: this.selectedDevice,
        theftAlert: theftAlert,
      })
      .subscribe((res) => {
        if (theftAlert) {
          this.parkingButtonShow = "green";
        } else {
          this.parkingButtonShow = "red";
        }
      });
  }

  openRightMenu() {
    document.getElementById("rightMenu").style.display = "block";
    document.getElementById("buttons").style.marginRight = "325px";
  }

  closeRightMenu() {
    document.getElementById("rightMenu").style.display = "none";
    document.getElementById("buttons").style.marginRight = "-7px";
  }

  saveRoutePath() {
    let dialogRef = this.dialog.open(ShoRoutePlanComponent, {
      width: "650px",
      height: "700px",
      data: { data: this.latlongObjArr, device: this.tempMapHistory[0] },
    });

    dialogRef.afterClosed().subscribe((result) => {});
  }

  workingHours = 0;
  workingHoursFunction1(device) {
    this.contactService
      .get(
        "/notifs/ignitionReportForMobile?from_date=" +
          this.datefrom +
          "&to_date=" +
          this.date2 +
          "&_u=" +
          this.useridd +
          "&device=" +
          device.Device_ID
      )
      .subscribe(
        (res: any) => {
          // console.log(res);
          this.workingHours =
            res.workingHours != "" && res.workingHours ? res.workingHours : 0;
        },
        (err) => {
          this.workingHours = 0;
          console.log(err);
        }
      );
  }

  workingHoursFunction2(device) {
    this.contactService
      .get(
        "/notifs/acReportForMobile?from_date=" +
          this.datefrom +
          "&to_date=" +
          this.date2 +
          "&_u=" +
          this.useridd +
          "&device=" +
          device.Device_ID
      )
      .subscribe(
        (res: any) => {
          this.workingHours =
            res.workingHours != "" && res.workingHours ? res.workingHours : 0;
        },
        (err) => {
          console.log(err);
        }
      );
  }

  async wait_time(t) {
    return new Promise((a, b) => {
      setTimeout(() => {
        a(new Date().getTime());
      }, t * 1000);
    });
  }
  async startSocketConnection(listofDevices) {
    let t_time: any = await this.wait_time(5);

    this.deviceToTrack = listofDevices;

    for (var x = 0; x < this.deviceToTrack.length; x++) {
      var newChannel = this.deviceToTrack[x].toString();
      var date = new Date().setHours(0, 0, 0, 0);

      this.socket.emit("initLive", newChannel, date);
      this.socket.on(newChannel, channelListener(newChannel));
    }
    var r;
    let that = this;
    function channelListener(newChannel) {
      return (msg, initData, deviceInfo) => {
        that.socketIOData = deviceInfo;
        if (deviceInfo && deviceInfo.Device_ID) {
          that.deviceList.map((dData) => {
            if (
              dData.Device_ID == deviceInfo.Device_ID &&
              deviceInfo.last_loc &&
              deviceInfo.last_loc.coordinates
            ) {
              dData.last_loc.coordinates = deviceInfo.last_loc.coordinates;
            }
          });
        }
        let checkedDevicesLength = that.deviceList.filter(
          (dMDevice) => dMDevice.checked
        );
        if (
          checkedDevicesLength.length == 1 &&
          deviceInfo.Device_ID == checkedDevicesLength[0].Device_ID
        ) {
          that.deviceList.filter(function (colHilight, i) {
            that.deviceList[i]["playPause"] = true;
            if (colHilight.Device_ID === checkedDevicesLength[0].Device_ID) {
              that.deviceList[i]["columnHighlight"] = true;
              if (msg["GPS positioned"]) {
                that.deviceList[i].gpsTracking = msg["GPS positioned"];
              }
              if (msg.ignition) {
                that.deviceList[i].last_ACC = msg.ignition;
              }
              if (msg.power) {
                that.deviceList[i].power = msg.power;
              }
              if (msg.speed) {
                that.deviceList[i].last_speed = msg.speed;
              }
              if (that.currentPage !== 2) {
                that.showSocketData = true;

                that.showSocketData = true;
                // date satellites ignition port
                if (msg.date == undefined) {
                  msg["date"] = colHilight.last_ping_on;
                }

                if (msg.satellites == undefined) {
                  msg["satellites"] = colHilight.satellites;
                }
                if (msg.ignition == undefined) {
                  msg["ignition"] = colHilight.last_ACC;
                }
                if (msg.port == undefined) {
                  msg["port"] = colHilight.port;
                }

                that.socketData = msg;
                that.getSystemLogs(colHilight);
                that.deviceCQ(colHilight);
                that.getRecentNotification(colHilight);
                that.getAddressBy(msg, deviceInfo);
              }
            } else {
              that.deviceList[i]["columnHighlight"] = false;
            }
          });
        }
      };
    }
  }
  removeSocketLister(list) {
    // list.forEach((item)=>{

    // })
    this.socket.removeAllListeners(list);
  }
  socketListnerHandler(event) {
    if (event.type == "add") {
      this.startSocketConnection(event.list);
    } else {
      this.removeSocketLister(event.list);
    }
  }
}
