// new location 
  maphistory(data) {
    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;

        this.contactService
          .getDistance(
            this.ddid,
            fromtime,
            totime,
            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);
            }

            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.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 = 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.datee = JSON.stringify(this.latlongObjArr[i].insertionTime);

              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;

              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 = 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);
              }

              var arr = [];
              cumDistance =
                (this.latlongObjArr[i].cummulative_distance
                  ? parseFloat(this.latlongObjArr[i].cummulative_distance)
                  : 0) + cumDistance;
              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 = [this.latlongObjArr[i].lng, this.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 (
                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) {
                }
              } 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.coloumnClicked === false) {
              tempData["dataArrayCoords"] = this.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;

            this.contactService
              .getDistance(
                this.ddid,
                fromtime,
                totime,
                this.satelliteDisabled ? this.satelite : undefined
              )
              .subscribe((data3) => {
                this.data2 = data3;

                // initialize();
                console.log(
                  "__________________",
                  this.data2,
                  this.distanceVariation
                );
                let a = Number(
                  this.data2["Distance"] ? this.data2["Distance"] : 0
                );

                if (this.coloumnClicked === false) {
                  tempData["mileage"] = a.toFixed(2);
                  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;

                this._openMapComponet.setHistoryTrack(
                  this._openMapComponet.uniqueIdForHistory,
                  this.tempMapHistory,
                  this.latLngLine,
                  this.tempMapHistory.length - 1
                );
                var playerSeekbar: any;
              });
          });
      }
      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>";
          // console.log("CONTENt",content)<div>Odo-:'+dataa+'
          // },2000)
          // var dataa
          //  console.log(outerThis.fromTIME,outerThis.stop_locationss,outerThis.counter,"))))))))))))))))");

          //      outerThis.contactService.getDistance(outerThis.ddid, outerThis.fromTIME, (outerThis.stop_locationss[l][2]).toISOString(),outerThis.satelliteDisabled?outerThis.satelite:undefined).subscribe((data3:any) => {
          //          console.log("DADADADADADADAD--->",data3);
          //          dataa=data3.Distance?data3.Distance:''
          //         content=content+`<div>Odo-:`+ data3.Distance?data3.Distance:''+'</div>'
          //      })

          google.maps.event.addListener(
            marker,
            "click",
            (function (marker, content, infowindow) {
              return function () {
                //       var dataa
                //       console.log(outerThis.fromTIME,outerThis.stop_locationss,outerThis.counter,"))))))))))))))))");

                //        outerThis.contactService.getDistance(outerThis.ddid, outerThis.fromTIME, (outerThis.stop_locationss[outerThis.counter][2]).toISOString(),outerThis.satelliteDisabled?outerThis.satelite:undefined).subscribe((data3:any) => {
                //            console.log("DADADADADADADAD--->",data3);
                //           dataa=data3.Distance?data3.Distance:''
                //         //  return data3
                // })
                // setTimeout(function(){
                // content=content+`<div>Odo-:`+ dataa+'</div>'
                // console.log(content,"+++");
                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);
  }
//    google history
/////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////
maphistory(data) {

    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 = [];
        
        try {
          
          this.path = flightPath.getPath();
        } catch (error) {
          console.log('flightPath.getPath()', error)
        }


        var cumulativeDistance = 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.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);
          }

          var arr = [];
          arr.push(this.latlongObjArr[i].lat);
          arr.push(this.latlongObjArr[i].lng);
          arr.push(this.latlongObjArr[i].speed);
          arr.push(this.latlongObjArr[i].cummulative ? this.latlongObjArr[i].cummulative.toFixed(2) : 0);
          arr.push(this.datee);
          arr.push(this.latlongObjArr[i].external_Battery);
          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,
              })
              this.markers.push(markersPasts);
              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.markers.push(markerCurrent)
              // 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),
              });
              this.markers.push(markerSrc);
              //  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) {
                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,
                })
                this.markers.push(markersPasts);
                markersPasts['infowindow'] = new google.maps.InfoWindow({ content: content });
                google.maps.event.addListener(markersPasts, 'click', function () {
                  // console.log("inside info window function 1");
                  this['infowindow'].open(map, this);
                });


              }
            }
            if (i == 1) {
              markerCurrent = new google.maps.Marker({
                position: new google.maps.LatLng(this.lat, this.lng),
                map: map,
                icon: iconDest
              });
              outerThis.markers.push(markerCurrent);
              // 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
              })
              outerThis.markers.push(markerSrc);
              outerThis.marker4 = markerSrc;
            }
          }
        }



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

        }

        // 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;

        this.contactService.getDistance(this.ddid, fromtime, totime, 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;
            tempData['aIndex'] = this.tempMapHistory.length;
            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;
          $(document).ready(function () {
            playerSeekbar = document.getElementById('slider1');
            console.log("ready!", playerSeekbar['value']);
            playerSeekbar.oninput = function () {

              zoomToObject(flightPath);
              outerThis.changeRange();

            }
          });
        })


      }
      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];
            })
           }
          
          // console.log('countercountercountercountercountercountercounter',counter,data3);
          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.latlongObjArr = data3;
          this.flag = 'init';
          initialize();
          this.Load = false;
          let cluster_arr = [];
          // console.log(flightPath.getPath());

          try {
          
            this.path = flightPath.getPath();
          } catch (error) {
            this.path = [];
            console.log('flightPath.getPath()', error)
          }
          var cumulativeDistance = 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.speed = this.latlongObjArr[i].speed + "Km/hr";
            this.im = this.latlongObjArr[i].imei;
            // console.log(this.latlongObjArr[i]);
            var insertionTime = moment(this.latlongObjArr[i].insTime).format('MMMM Do YYYY, h:mm:ss a');
            var raw = this.latlongObjArr[i].raw;
            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(this.latlongObjArr[i],"lakskalskalkl");
            // var insTime = new Date(this.datee);
            this.datee = moment(JSON.parse(this.datee)).format('MMMM Do YYYY, h:mm:ss a');
            var lastLat = this.latlongObjArr[i].lat
            var lastlong = this.latlongObjArr[i].lng
            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 = '';
            // content=`<div id="content"><div id="bodyContent"><div><br><b>DEVICE NAME :$d_name`
            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>INSERTION TIME : ` + insertionTime +
              `</b><br><b>RAW : ` + '<span style="word-break: break-all;"  id="display_row' + this.latlongObjArr[i]._id + '"></span><a id="' + this.latlongObjArr[i]._id + '" style="color: blue;text-decoration: underline;" onclick = "window.angularComponentRef.zone.run(() => {window.angularComponentRef.component.GetRowPacketEvent(\'' + this.latlongObjArr[i]._id + '\');})" > Get Raw Data </a>' +
              `</b><br><b style="margin-bottom:10px" id="addressBinding">Address : `
              + this.contentAdd + '</b></div></b><br>'
              + '<button style="margin-top:10px;background-color: blue;color: white;padding: 5px;" onclick="window.angularComponentRef.zone.run(() => {window.angularComponentRef.component.addpoi(\'' + lastLat + ',' + lastlong + '\');})">ADD POI</button></div></div></div>'
            // '<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>'
            // <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>

            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);
            }

            var arr = [];
            arr.push(this.latlongObjArr[i].lat);
            arr.push(this.latlongObjArr[i].lng);
            arr.push(this.latlongObjArr[i].speed);
            arr.push(this.latlongObjArr[i].cummulative ? this.latlongObjArr[i].cummulative.toFixed(2) : 0);
            arr.push(this.datee);
            arr.push(this.latlongObjArr[i].external_Battery);
            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';
            // iconSrc['infowindow'] = new google.maps.InfoWindow({ content: contentString });
            // '/assets/images/liveTrackIcons/ocar.png';
            // ======================added ========================================
            // this.lat = this.latlongObjArr[i].lat;
            // this.lng = this.latlongObjArr[i].lng;       
            // this.path.push(new google.maps.LatLng(this.lat, this.lng));

            // =====================================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 markersPast = 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,
                })

                markersPast['infowindow'] = new google.maps.InfoWindow({ content: content });
                this.markers.push(markersPast);
                google.maps.event.addListener(markersPast, 'click', function () {


                  var lattitude = markersPast.position.lat();
                  var longitude = markersPast.position.lng();
                  var latlng_1 =
                  {
                    "lat": lattitude,
                    "long": longitude
                  }
                  let addressRes = outerThis.contactService.latLongAddress[longitude+'_'+lattitude]; 
                  

                    if (!(addressRes && addressRes.address)) {
                      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 = addressRes.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)

                    }

                  
                })

              }



              if (i == 1) {
                markerCurrent = new google.maps.Marker({
                  position: new google.maps.LatLng(this.lat, this.lng),
                  map: map,
                  icon: iconDest
                });
                outerThis.markers.push(markerCurrent);
                // 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),
                });
                outerThis.markers.push(markerSrc);
                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) {
                  var markersPast = 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,
                  })
                  this.markers.push(markersPast);
                  markersPast['infowindow'] = new google.maps.InfoWindow({ content: content });
                  google.maps.event.addListener(markersPast, 'click', function () {
                    // console.log("inside info window function 1");
                    this['infowindow'].open(map, this);
                  });


                }
              }
              if (i == 1) {
                markerCurrent = new google.maps.Marker({
                  position: new google.maps.LatLng(this.lat, this.lng),
                  map: map,
                  icon: iconDest
                });
                outerThis.markers.push(markerCurrent);
                // 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
                })
                outerThis.marker4 = markerSrc;
                outerThis.markers.push(markerSrc);
              }
            }
          }

          if (this.coloumnClicked === false) {
            tempData['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;

          this.contactService.getDistance(this.ddid, fromtime, totime, this.satelliteDisabled ? this.satelite : undefined).subscribe((data3) => {

            this.data2 = data3;

            // initialize();
            let a = Number(this.data2["Distance"] ? this.data2["Distance"] : 0);
            // 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;
            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;
            $(document).ready(function () {
              playerSeekbar = document.getElementById('slider1');
              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;
      // console.log(deviceObjectid);

      if (this.idleColor === true) {
        this.idlePlot(fromtime, totime, deviceObjectid, min_time, map)
      }
      var stop_locations = [];
      if (this.parkingColor === true) {
        //     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();
        // console.log('this.useriddthis.useridd',this.useridd,"IIIIIIIIIIIIIIIi",this.dev_id.id?this.dev_id.id: this.dev_id._id);
        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)
          // this.contactService.stoppage_report(fromtime,totime,userid,this.dev_id.id?this.dev_id.id: this.dev_id._id)
          .subscribe((res) => {
            // console.log("===========================>",res,this.parkingArr);
            // this.parkingArr=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);


            }
            // 
            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)
              // }
              initParking();
              // console.log("initParking")
            } else {
              // console.log("In Else part initParking",stop_locations)
            }
          })
      }

    }

    // console.log(totime)
    this.latLongArr2 = [];
    var customTxt;
    var txt;
    function geocodePosition(pos, callback) {
      try {
        var geocoder = new google.maps.Geocoder();
        geocoder.geocode({
          latLng: pos
        }, function (responses) {
          callback(responses && responses[0] && responses[0].formatted_address ? responses[0].formatted_address : null)

        });
      } catch (error) {
        callback(null)
      }

    }
    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


        var index = stop_locations.length
        for (l = 0; l < stop_locations.length; l++) {
          index--;
          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,
            label: {
              color: '#000', fontSize: '12px', fontWeight: '600',
              text: index.toString()
            }

          });
          
          outerThis.markers.push(marker);
          google.maps.event.addListener(marker, 'dragend', function () {

            this.geocodePosition(marker.getPosition());
          });
          if(outerThis.historyMap && marker) {
            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>'
          // console.log("CONTENt",content)<div>Odo-:'+dataa+'
          // },2000)
          // var dataa
          //  console.log(outerThis.fromTIME,outerThis.stop_locationss,outerThis.counter,"))))))))))))))))");

          //      outerThis.contactService.getDistance(outerThis.ddid, outerThis.fromTIME, (outerThis.stop_locationss[l][2]).toISOString(),outerThis.satelliteDisabled?outerThis.satelite:undefined).subscribe((data3:any) => {
          //  console.log("DADADADADADADAD--->",data3);
          //          dataa=data3.Distance?data3.Distance:''
          //         content=content+`<div>Odo-:`+ data3.Distance?data3.Distance:''+'</div>'
          //      })

          google.maps.event.addListener(marker, 'click', (function (marker, content, infowindow) {
            return function () {
              //       var dataa
              // console.log(outerThis.fromTIME,outerThis.stop_locationss,outerThis.counter,"))))))))))))))))");

              //        outerThis.contactService.getDistance(outerThis.ddid, outerThis.fromTIME, (outerThis.stop_locationss[outerThis.counter][2]).toISOString(),outerThis.satelliteDisabled?outerThis.satelite:undefined).subscribe((data3:any) => {
              //  console.log("DADADADADADADAD--->",data3);
              //           dataa=data3.Distance?data3.Distance:''
              //         //  return data3
              // })
              // setTimeout(function(){
              // content=content+`<div>Odo-:`+ dataa+'</div>'
              // console.log(content,"+++");
              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: 8,
        center: new google.maps.LatLng(18.602941, 73.777147),
        mapTypeId: google.maps.MapTypeId.ROADMAP
      };
      map = outerThis.getMapObject(myOptions);
      //map = new google.maps.Map(document.getElementById('map'), myOptions);
      // console.log('mapmapmapmapmapmapmapmapmapmapmapmapmapmap',map);
      outerThis.historyMap = map;
      var trafficLayer = new google.maps.TrafficLayer();
      if (outerThis.isTraffic) {
        trafficLayer.setMap(map);
      } else {
        trafficLayer.setMap(null);
      }


      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"
        });
        outerThis.markers.push(marker);
        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"
        });
        outerThis.markers.push(marker1);
        allSourceDestinationMarkers.push(marker1);

        flightPath = new google.maps.Polyline({
          path: mapData,
          geodesic: true,
          strokeColor: strokeColor,
          strokeOpacity: 1.0,
          strokeWeight: 6
        });
        outerThis.polyLinePathObject = flightPath;
        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);
        outerThis.markers.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'
        // }
      ],

    });
    
    outerThis.polyLinePathObject = flightPath;
    outerThis.polyLinePathArrayNew[(new Date()).getTime()] = flightPath;
    outerThis.polyLinePathArray[outerThis.tempMapHistory.length] = flightPath;
    
    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);

  }