en mi modulo angular estudio-jlr.component.html y.ts he añadido el componente <app-network-query-map> necesito que al abrir estudio-jlr.component añada al mapbox dos pines, uno en la latitud 
latitud: 40.338383
longitud: -3.373262
y otro en 
latitud: 40.494392
longitud: -3.346994

el app-network-query-map component contiene un mapbox el cual te paso su código a continuación.

import {
  AfterViewChecked,
  Component,
  EventEmitter,
  HostListener,
  Input,
  OnDestroy,
  OnInit,
  Output,
  ViewEncapsulation,
} from "@angular/core";
import * as mapboxgl from "mapbox-gl";
import { environment } from "../../../../../environments/environment";
import { MapService } from "../../../../../services/map.service";
import MapboxLanguage from '@mapbox/mapbox-gl-language';
import * as _ from "lodash";
import { NGXLogger } from "ngx-logger";
import html2canvas from "html2canvas";
import { TranslateService } from "@ngx-translate/core";
import { ToastrService } from "ngx-toastr";
import { MatDialog, MatDialogConfig } from "@angular/material/dialog";
import { ColorChangeModalComponent } from "../../../color-change-modal/color-change-modal.component";
import MapboxGeocoder from "@mapbox/mapbox-gl-geocoder";
import { ThemeService } from "../../../../../services/theme.service";
import { UserService } from "../../../../../services/user.service";
import { NetworkAnalysisService } from "src/services/network-analysis.service";
import { NetworkQueryService } from "src/services/network-query.service";
import { NetworksService } from "src/services/networks.service";
import { NetworksPlusService } from "src/services/network-plus.service";
import { sourceMap, groupMap, layerMap } from "src/app/interfaces/interfaces";
import { ColorPickerModalComponent } from "../../../color-change-modal/color-picker-modal/color-picker-modal.component";
import { throwToolbarMixedModesError } from "@angular/material/toolbar";
import { elements } from "devexpress-dashboard/model/index.metadata";
import { Workbook } from "exceljs";
import { exportDataGrid } from "devextreme/excel_exporter";
import { saveAs } from 'file-saver';
import { DataLoadingService } from "src/services/dialog.service";

@Component({
  selector: 'app-network-query-map',
  templateUrl: './network-query-map.component.html',
  styleUrls: ['./network-query-map.component.scss'],
  encapsulation: ViewEncapsulation.None
})

export class NetworkQueryMapComponent implements OnInit {
  @Input() selectedTimer: number;
  @Input() idMap: string;
  @Input() country_map: string;

  @Output() hasRemovedLayer = new EventEmitter<any>();
  @Output() loadEnding = new EventEmitter<any>();
  @Output() clickEvenEmit = new EventEmitter<any>();
  @Output() closeEvent = new EventEmitter<any>();


  public layers = [];
  public layersLegend = [];
  public legendTitle: string;
  public legendLayerTitle: string;
  public legendDrivingTitle: string;
  public rankLegend = [];
  public showLegend: boolean;
  public mapTableData: object[] = [];

  private activeSource: string;
  private borderColors: object;
  private clickedElements = [];
  private colorMarker = environment.map.defaultColorMarker;
  private customMarkersList = [];
  private dataCpProvince = {};
  private dataIdGeometry = {};
  private dataLabels = {};
  private filtersToLayers = {};
  private findByCpMarkers = [];
  private geoCoder: MapboxGeocoder;
  private isochroneColor = environment.map.isochroneDefaultColor;
  private isoChroneSourceArray = [];
  private labelsShown = false;
  private labelSource = [];
  public map: mapboxgl.Map;
  private mapBox = mapboxgl as typeof mapboxgl;
  private mapLocalData = {};
  private markerColorsAvailable = [
    "#6495ED",
    "#808000",
    "#FF7F50",
    "#A9A9A9",
    "#8B008B",
    "#FF8C00",
    "#FFD700",
    "#0000CD",
    "#FF00FF",
    "#00FF7F",
    "#FF69B4",
    "#7FFF00",
  ];
  private markerColorAux = [];
  private markersList = [];
  private modalColors = [];
  private popup: mapboxgl.Popup;
  private popupPin: mapboxgl.Popup;
  private pos4Layers = [];
  private hoverIds = [];
  private isInit = false;
  private sourceCpos = "cpos";
  private sourceProv = "prov";
  private sourceMuni = "muni";
  private territoriesColorsAux = [];
  public territoriesColorsAvailable = [
    "#C6282899",
    "#FF00FF",
    "#000000",
    "#8B4513",
    "#483D8B",
    "#FF8C00",
  ];
  private userData: object;
  private hoveredStateId = null;
  private dataArray = [];
  public rangeArray = [];
  private click: any;
  private labelArray = [];
  private markersLabelArray = [];
  public selectedItemData: any;
  public mapTableColumns: object[] = [];
  public cpsArray: any[] = [];
  public dataMap = [];
  public showExportSpinner = false;
  public loading: boolean;
  public selectedColor = '#c62828';
  public mapIdSelected: string = '';
  private marker: any;
  public datosJson;
  private layerArray = [];
  public legendArray = [];
  private sourceArray = [];
  public objGroups = {
    groups: []
  }
  public showGridDatabase = false;
  public selectedTerrDataSource: any;
  public gridDataBaseheight = 330;
  private y = 100;
  private oldY = 0;
  private grabber = false;



  @Input() showProvincias: string;
  @Input() showMunicipios: string;
  @Input() showCP: string;

  constructor(
    private mapService: MapService,
    private logger: NGXLogger,
    private translateService: TranslateService,
    private toastr: ToastrService,
    private dialog: MatDialog,
    private tema: ThemeService,
    public userService: UserService,
    private networkService: NetworksService,
    private networkQueryService: NetworkQueryService,
    public translate: TranslateService,
    private dataLoadingService: DataLoadingService
  ) { }

  public addBordersTerritory(territory: any, sourceUrl: string, sourceLayerName: string) {
    const nameSource = territory['levelName'] + '-source';
    const nameGroup = territory['levelName'] + '-' + this.translateService.instant('ANALYSIS_MAP.BORDERS');
    if (this.map.getSource(nameSource) === undefined) {
      this.map.addSource(nameSource, {
        type: 'vector',
        url: sourceUrl
      });
      this.addSource(nameSource);
      this.addGroup(nameGroup, nameSource, 'border-map', this.territoriesColorsAux[0]);
      this.addLayer(nameSource, sourceLayerName, nameGroup, territory);
    } else {
      this.addGroup(nameGroup, nameSource, 'border-map', this.territoriesColorsAux[0]);
      this.addLayer(nameSource, sourceLayerName, nameGroup, territory);
    }
  }

  private addLayer(nameSource: string, sourceLayerName: string, nameGroup: string, territory: any) {
    this.map.addLayer({
      id: nameGroup,
      type: 'fill',
      source: nameSource,
      'source-layer': sourceLayerName,
      filter: ['all'],
      paint: {
        'fill-color': 'rgba(1, 1, 1, 0)',
        'fill-opacity': [
          'case',
          ['boolean', ['feature-state', 'hover'], false],
          2,
          0.6,
        ],
        'fill-outline-color': this.territoriesColorsAux[0],
      },
    });
    if ((territory['numLevel'] === 10 && this.userService.getLanguageRole() === 'DE')
      || (territory['numLevel'] === 9 && this.userService.getLanguageRole() === 'ES')) {
      this.map.on("click", nameGroup, (e) => {
        this.clickEvent(e, nameGroup, nameSource, nameGroup);
      });
    }
    this.map.on("mousemove", nameGroup, (e) => {
      this.mouseMove(e, nameSource, sourceLayerName, nameGroup);
    });
    this.map.on("mouseleave", nameGroup, (e) => {
      this.mouseLeave(e, nameSource, sourceLayerName, nameGroup);
    });
    this.addDataLayer(nameGroup, nameGroup, nameSource);
  }

  public getLevelSevenSource() {
    let toReturn = environment.map.urlBoundariesProvinces.source;
    if (this.userService.getLanguageRole() === "DE") {
      toReturn = environment.map.urlBoundariesGermanyFederalStates.source;
    }
    return toReturn;
  }

  public getLevelSevenLayer() {
    let toReturn = environment.map.urlBoundariesProvinces.layer;
    if (this.userService.getLanguageRole() === "DE") {
      toReturn = environment.map.urlBoundariesGermanyFederalStates.layer;
    }
    return toReturn;
  }

  public getLevelEightSource() {
    let toReturn = environment.map.urlBoundariesMunicipality.source;
    if (this.userService.getLanguageRole() === "DE") {
      toReturn = environment.map.urlBoundariesGermanyDistricts.source;
    }
    return toReturn;
  }

  public getLevelEigthLayer() {
    let toReturn = environment.map.urlBoundariesMunicipality.layer;
    if (this.userService.getLanguageRole() === "DE") {
      toReturn = environment.map.urlBoundariesGermanyDistricts.layer;
    }
    return toReturn;
  }

  public getLevelNineSource() {
    let toReturn = environment.map.urlBoundariesCP.source;
    if (this.userService.getLanguageRole() === "DE") {
      toReturn = environment.map.urlBoundariesGermanyMunicipalities.source;
    }
    return toReturn;
  }

  public getLevelNineLayer() {
    let toReturn = environment.map.urlBoundariesCP.layer;
    if (this.userService.getLanguageRole() === "DE") {
      toReturn = environment.map.urlBoundariesGermanyMunicipalities.layer;
    }
    return toReturn;
  }

  public getBordersGroupedCPs(territory: any) {
    const objToSend = {
      filters: [],
      sqlWhereDefault: 'ID_USER',
      numlevelToSearch: territory['numLevel'],
      country_map: this.userService.getLanguageRole(),
    };
    this.loading = true;
    this.networkService.getBordersGroupedCPs(objToSend).subscribe(response => {
      if (response) {
        let geoData: any;
        geoData = {
          features: [],
          type: 'FeatureCollection'
        };
        _.forEach(response['groups'], obj => {
          if (obj['boundaries'] !== undefined && obj['boundaries'] !== null) {
            if (obj['boundaries'].length !== 0) {
              const objToSend = {
                mode: 'on',
                name: this.translateService.instant('ANALYSIS_MAP.CONCESSIONS'),
                type: environment.map.typesBorders.levelNet,
                groups: obj
              };
              geoData['features'].push(this.extractBoundaries(objToSend));
            }
          }
        });
        const nameSource = territory['levelName'];
        this.addBordersBoundaries(geoData, nameSource);
        this.loading = false;
      }
    });
  }

  private addBordersBoundaries(geoData: any, levelName: any) {
    const nameSource = levelName + '-source';
    const nameGroup = levelName + '-' + this.translateService.instant('ANALYSIS_MAP.BORDERS');
    if (geoData['features'].length !== 0) {
      if (this.map.getSource(nameSource) === undefined) { // Cuando no existe el source lo creamos y añadimos el grupo
        this.addSource(nameSource);
        this.map.addSource(nameSource, {
          type: 'geojson',
          data: geoData
        });
        this.addGroup(nameGroup, nameSource, 'border', this.territoriesColorsAux[0]);
      } else {  // Cuando existe el source lo eliminamos porque es quien tiene los bordes, y volvemos a crear todo
        setTimeout(() => {
          this.map.removeLayer(nameSource);
        }, 100);
        setTimeout(() => {
          this.map.removeSource(nameSource);
          _.remove(this.dataMap, function (sourceMap) { return sourceMap['sourceName'] === nameSource });
        }, 200);
        setTimeout(() => {
          this.addSource(nameSource);
          this.map.addSource(nameSource, {
            type: 'geojson',
            data: geoData
          });
          this.addGroup(nameGroup, nameSource, 'border', this.territoriesColorsAux[0]);
          setTimeout(() => {
            this.map.addLayer({
              id: nameGroup,
              type: 'fill',
              source: nameSource,
              paint: {
                'fill-color': 'rgba(1, 1, 1, 0)',
                'fill-opacity': [
                  'case',
                  ['boolean', ['feature-state', 'hover'], false],
                  2,
                  0.8,
                ],
                'fill-outline-color': this.territoriesColorsAux[0],
              }
            });
            this.addDataLayer(nameGroup, nameGroup, nameSource);
          }, 100);
        }, 300);
      }
      if (this.map.getLayer(nameGroup) === undefined) {
        this.map.addLayer({
          id: nameGroup,
          type: 'fill',
          source: nameSource,
          paint: {
            'fill-color': 'rgba(1, 1, 1, 0)',
            'fill-opacity': [
              'case',
              ['boolean', ['feature-state', 'hover'], false],
              2,
              0.8,
            ],
            'fill-outline-color': this.territoriesColorsAux[0],
          }
        });
        this.addDataLayer(nameGroup, nameGroup, nameSource);
      }
    }
  }


  private isEventGroup(groupName: any) {
    let toReturn = {};
    _.forEach(this.dataMap, source => {
      _.forEach(source['groups'], groupEach => {
        if (groupEach['groupName'] === groupName) {
          toReturn = groupEach;
        }
      });
    });
    return toReturn;
  }

  private getFeatureType(features: Array<any>) {
    let toReturn = undefined;
    _.forEach(features, element => {
      if (this.userService.getLanguageRole() === 'DE') {
        if (element['properties']['Stab_nr'] !== undefined) {
          toReturn = element;
        }
      } else if (this.userService.getLanguageRole() === 'ES') {
        if (element['properties']['COD_POSTAL'] !== undefined) {
          toReturn = element;
        }
      }
    });
    return toReturn;
  }

  private getSourceDataMap(sourceName: string) {
    let toReturn = undefined;
    _.forEach(this.dataMap, source => {
      if (source['sourceName'] === sourceName) {
        toReturn = source;
      }
    });
    return toReturn;
  }

  private createMarkers(group: any, value: boolean) {
    if (value) {
      _.forEach(group["labels"], (obj, i) => {
        const el = document.createElement("div");
        el.id = i.toString();
        el.style.backgroundColor = "#FFF";
        el.style.width = "auto";
        el.style.height = "18px";
        el.style.padding = "0px 3px 1px 3px";
        el.style.borderRadius = "3px";
        el.style.opacity = ".7";
        el.style.fontSize = "10px";
        el.style.fontWeight = "bold";
        el.innerText = obj["labelName"];
        const lngLat = new mapboxgl.LngLat(
          obj["labelCoordenates"]["x"],
          obj["labelCoordenates"]["y"]
        );
        const marker = new mapboxgl.Marker({
          element: el,
          draggable: true,
        })
          .setLngLat(lngLat)
          .addTo(this.map);
        group["markers"].push(marker);
      });
    } else {
      _.forEach(group["markers"], (m, index) => {
        m.remove();
        if (group["markers"].length === index + 1) {
          group["markers"] = [];
        }
      });
    }
  }



  private isExistLayer(idLayer) {
    let toReturn = false;
    const index = _.findIndex(this.layerArray, { id: idLayer });
    if (index !== -1) {
      toReturn = true;
    }
    return toReturn;
  }

  private generateRandomColors(numColors: number): string[] {
    let index = 1;
    const colors = [];
    while (index <= numColors) {
      const hue = index * 137.508;
      colors.push(`hsl(${hue},50%,75%)`);
      index++;
    }
    return colors;

  }

  private checkLayersToShow() {
    if (this.showProvincias) {
      this.showProvinceLayer();
    }
    if (this.showMunicipios) {
      this.showMuniLayer();
    }
    if (this.showCP) {
      this.showCPLayer();
    }
  }

  showProvinceLayer() {
    this.createSource('provincias', 'vector', environment.map.urlBoundariesProvinces.source);
    if (this.isExistLayer('provincias-fill')) {
      this.map.removeLayer('provincias-fill');
      _.remove(this.layerArray, { id: 'provincias-fill' });
    }
    this.map.addLayer(
      {
        id: 'provincias-fill',
        type: 'fill',
        source: 'provincias',
        'source-layer': environment.map.urlBoundariesProvinces.layer,
        paint: {
          'fill-color': 'rgba(1, 1, 1, 0)',
          'fill-opacity': [
            'case',
            ['boolean', ['feature-state', 'hover'], false],
            2,
            0.8,
          ],
          'fill-outline-color': this.tema.getProperty('--map-outline-color-strong'),
        },
        filter: ['all'],
      }
    );
    this.layerArray.push({ id: 'provincias-fill' });
  }

  showMuniLayer() {
    this.createSource('municipios', 'vector', environment.map.urlBoundariesMunicipality.source);
    if (this.isExistLayer('municipios-fill')) {
      this.map.removeLayer('municipios-fill');
      _.remove(this.layerArray, { id: 'municipios-fill' });
    }
    this.map.addLayer(
      {
        id: 'municipios-fill',
        type: 'fill',
        source: 'municipios',
        'source-layer': environment.map.urlBoundariesMunicipality.layer,
        paint: {
          'fill-color': 'rgba(1, 1, 1, 0)',
          'fill-opacity': [
            'case',
            ['boolean', ['feature-state', 'hover'], false],
            2,
            0.8,
          ],
          'fill-outline-color': this.tema.getProperty('--map-outline-color-strong'),
        },
        filter: ['all'],
      }
    );
    this.layerArray.push({ id: 'municipios-fill' });
  }

  showCPLayer() {
    this.createSource('cp', 'vector', environment.map.urlBoundariesCP.source);
    if (this.isExistLayer('cp-fill')) {
      this.map.removeLayer('cp-fill');
      _.remove(this.layerArray, { id: 'cp-fill' });
    }
    this.map.addLayer(
      {
        id: 'cp-fill',
        type: 'fill',
        source: 'cp',
        'source-layer': environment.map.urlBoundariesCP.layer,
        paint: {
          'fill-color': 'rgba(1, 1, 1, 0)',
          'fill-opacity': [
            'case',
            ['boolean', ['feature-state', 'hover'], false],
            2,
            0.5,
          ],
          'fill-outline-color': this.tema.getProperty('--map-outline-color-strong'),
        },
        filter: ['all'],
      }
    );
    this.layerArray.push({ id: 'cp-fill' });
  }

  private createSource(idSource, typeSource, urlSource) {
    if (!this.isExistSource(idSource)) {
      this.map.addSource(idSource, {
        type: typeSource,
        url: urlSource // environment.map.urlBoundariesCP.source,
      });
      this.sourceArray.push({ id: idSource });
    }
  }

  private isExistSource(idSource) {
    let toReturn = false;
    const index = _.findIndex(this.sourceArray, { id: idSource });
    if (index !== -1) {
      toReturn = true;
    }
    return toReturn;
  }


  public setDataBaseDataSource(netInUse: any, selectedNet: any) {
    this.selectedTerrDataSource = [];
    this.networkQueryService.getTerritoryByIdRed(netInUse.idnet, netInUse.schema_bbdd, selectedNet.nivel1_id, selectedNet.nivel2_id, selectedNet.nivel3_id, selectedNet.nivel4_id).subscribe(
      (res) => {
        this.selectedTerrDataSource = res;
      },
      (err) => {
        if (
          !_.get(err, 'status') ||
          !_.includes([401, 403], _.get(err, 'status'))
        ) {
          this.toastr.error(
            this.translateService.instant('NETWORK_QUERY.DATABASE_ERROR')
          );
        }
      }
    )
  }

  public getCpostLevel1(netInUse: any, selectedNet: any) {
    this.objGroups = {
      groups: []
    };
    if (selectedNet.items !== null) {
      selectedNet.items.forEach((item, index) => {
          this.networkQueryService.getNetworkMapId(netInUse.idnet, netInUse.schema_bbdd, item.nivel1_id, item.nivel2_id).subscribe(
            (res) => {
              if (res['mapIdList'].length == 0) {
                this.toastr.info(
                  this.translateService.instant('NETWORK_QUERY.UNNASIGN_TERRITORY'),undefined, {
                    positionClass: 'toast-top-center'
                  }
                );
                // this.closeEvent.emit();
                this.dataLoadingService.closeDataLoadingDialog();

              } else {
                // Se vuelve a comprobar si hay territorios vacíos para mostrar el mensaje debido al bucle
                if (res['mapIdList'].length == 0) {
                  this.toastr.info(
                    this.translateService.instant('NETWORK_QUERY.UNNASIGN_TERRITORY'),undefined, {
                      positionClass: 'toast-top-center'
                    }
                  );
                }          
                let obj = {
                  elements: [],
                  labelName: item.nombre,
                  labelCoordenates: [res['labelCoordenates'][0]]
                }
                res['mapIdList'].forEach(cpost => {
                  obj.elements.push(cpost.elements[0]);
                });
                this.objGroups.groups.push(obj);
                if (index + 1 === selectedNet.items.length) {
                  this.addFillLayerGroupedByZipCode(this.objGroups, selectedNet.nombre);
                }
                // this.closeEvent.emit();
                this.dataLoadingService.closeDataLoadingDialog();

            }
            }
          )
      });
    } else {
      this.networkQueryService.getNetworkMapId(netInUse.idnet, netInUse.schema_bbdd, selectedNet.nivel1_id).subscribe(
        (res) => {
          if (res['mapIdList'].length == 0) {
            this.toastr.info(
              this.translateService.instant('NETWORK_QUERY.UNNASIGN_TERRITORY'),undefined, {
                positionClass: 'toast-top-center'
              }
            );
            // this.closeEvent.emit();
            this.dataLoadingService.closeDataLoadingDialog();

          } else {
            // Se vuelve a comprobar si hay territorios vacíos para mostrar el mensaje debido al bucle
            if (res['mapIdList'].length == 0) {
              this.toastr.info(
                this.translateService.instant('NETWORK_QUERY.UNNASIGN_TERRITORY'),undefined, {
                  positionClass: 'toast-top-center'
                }
              );
            }   
          let obj = {
            elements: [],
            labelName: selectedNet.nombre,
            labelCoordenates: [res['labelCoordenates'][0]]
          }
          res['mapIdList'].forEach(cpost => {
            obj.elements.push(cpost.elements[0]);
          });
          this.objGroups.groups.push(obj);
          this.addFillLayerGroupedByZipCode(this.objGroups, selectedNet.nombre);
          // this.closeEvent.emit();
          this.dataLoadingService.closeDataLoadingDialog();
        }
        }
      )
    }
  }


  public getCpostLevel2(netInUse: any, selectedNet: any) {
    this.objGroups = {
      groups: []
    };

    if (selectedNet.items !== null) {
      selectedNet.items.forEach((item, index) => {
          this.networkQueryService.getNetworkMapId(netInUse.idnet, netInUse.schema_bbdd, item.nivel1_id, item.nivel2_id, item.nivel3_id).subscribe(
            (res) => {
              if (res['mapIdList'].length == 0) {
                this.toastr.info(
                  this.translateService.instant('NETWORK_QUERY.UNNASIGN_TERRITORY'),undefined, {
                    positionClass: 'toast-top-center'
                  }
                );
                // this.closeEvent.emit();
                this.dataLoadingService.closeDataLoadingDialog();
              } else {
                  // Se vuelve a comprobar si hay territorios vacíos para mostrar el mensaje debido al bucle
                  if (res['mapIdList'].length == 0) {
                    this.toastr.info(
                      this.translateService.instant('NETWORK_QUERY.UNNASIGN_TERRITORY'),undefined, {
                        positionClass: 'toast-top-center'
                      }
                    );
                  }   
                let obj = {
                  elements: [],
                  labelName: item.nombre,
                  labelCoordenates: [res['labelCoordenates'][0]]
                }
                res['mapIdList'].forEach(cpost => {
                  obj.elements.push(cpost.elements[0]);
                });
                this.objGroups.groups.push(obj);
                if (index + 1 === selectedNet.items.length) {
                  this.addFillLayerGroupedByZipCode(this.objGroups, selectedNet.nombre);
                }
                // this.closeEvent.emit();
                this.dataLoadingService.closeDataLoadingDialog();
              }
            }
          )
      });
    } else {
      this.networkQueryService.getNetworkMapId(netInUse.idnet, netInUse.schema_bbdd, selectedNet.nivel1_id, selectedNet.nivel2_id).subscribe(
        (res) => {
          if (res['mapIdList'].length == 0) {
            this.toastr.info(
              this.translateService.instant('NETWORK_QUERY.UNNASIGN_TERRITORY'),undefined, {
                positionClass: 'toast-top-center'
              }
            );
            // this.closeEvent.emit();
            this.dataLoadingService.closeDataLoadingDialog();

          } else {
            // Se vuelve a comprobar si hay territorios vacíos para mostrar el mensaje debido al bucle
            if (res['mapIdList'].length == 0) {
              this.toastr.info(
                this.translateService.instant('NETWORK_QUERY.UNNASIGN_TERRITORY'),undefined, {
                  positionClass: 'toast-top-center'
                }
              );
            }   
          let obj = {
            elements: [],
            labelName: selectedNet.nombre,
            labelCoordenates: [res['labelCoordenates'][0]]
          }
          res['mapIdList'].forEach(cpost => {
            obj.elements.push(cpost.elements[0]);
          });
          this.objGroups.groups.push(obj);
          this.addFillLayerGroupedByZipCode(this.objGroups, selectedNet.nombre);
          // this.closeEvent.emit();
          this.dataLoadingService.closeDataLoadingDialog();

          }
        }
      )
    };
  }



  public getCpostLevel3(netInUse: any, selectedNet: any) {

    // this.setDataBaseDataSource(netInUse,selectedNet);

    this.objGroups = {
      groups: []
    };
    if (selectedNet.items !== null) {
      selectedNet.items.forEach((item, index) => {
          this.networkQueryService.getNetworkMapId(netInUse.idnet, netInUse.schema_bbdd, item.nivel1_id, item.nivel2_id, item.nivel3_id,item.nivel4_id).subscribe(
            (res) => {
              if (res['mapIdList'].length == 0) {
                this.toastr.info(
                  this.translateService.instant('NETWORK_QUERY.UNNASIGN_TERRITORY'),undefined, {
                    positionClass: 'toast-top-center'
                  }
                );
                // this.closeEvent.emit();
                this.dataLoadingService.closeDataLoadingDialog();

              } else {
                // Se vuelve a comprobar si hay territorios vacíos para mostrar el mensaje debido al bucle
                if (res['mapIdList'].length == 0) {
                  this.toastr.info(
                    this.translateService.instant('NETWORK_QUERY.UNNASIGN_TERRITORY'),undefined, {
                      positionClass: 'toast-top-center'
                    }
                  );
                }   
              let obj = {
                elements: [],
                labelName: item.nombre,
                labelCoordenates: [res['labelCoordenates'][0]]
              }
              res['mapIdList'].forEach(cpost => {
                obj.elements.push(cpost.elements[0]);
              });
              this.objGroups.groups.push(obj);
              if (index + 1 === selectedNet.items.length) {
                this.addFillLayerGroupedByZipCode(this.objGroups, selectedNet.nombre);
              }
              // this.closeEvent.emit();
              this.dataLoadingService.closeDataLoadingDialog();

            }
          }
          )
      });
    } else {
      this.networkQueryService.getNetworkMapId(netInUse.idnet, netInUse.schema_bbdd, selectedNet.nivel1_id, selectedNet.nivel2_id, selectedNet.nivel3_id).subscribe(
        (res) => {
          if (res['mapIdList'].length == 0) {
            this.toastr.info(
              this.translateService.instant('NETWORK_QUERY.UNNASIGN_TERRITORY'),undefined, {
                positionClass: 'toast-top-center'
              }
            );
            // this.closeEvent.emit();
            this.dataLoadingService.closeDataLoadingDialog();

          } else {
            // Se vuelve a comprobar si hay territorios vacíos para mostrar el mensaje debido al bucle
            if (res['mapIdList'].length == 0) {
              this.toastr.info(
                this.translateService.instant('NETWORK_QUERY.UNNASIGN_TERRITORY'),undefined, {
                  positionClass: 'toast-top-center'
                }
              );
            }   
          let obj = {
            elements: [],
            labelName: selectedNet.nombre,
            labelCoordenates: [res['labelCoordenates'][0]]
          }
          res['mapIdList'].forEach(cpost => {
            obj.elements.push(cpost.elements[0]);
          });
          this.objGroups.groups.push(obj);
          this.addFillLayerGroupedByZipCode(this.objGroups, selectedNet.nombre);
          // this.closeEvent.emit();
          this.dataLoadingService.closeDataLoadingDialog();

          }
        }
      )
    };
  }


  public getCpostLevel4(netInUse: any, selectedNet: any) {
    this.objGroups = {
      groups: []
    };

    this.networkQueryService.getNetworkMapId(netInUse.idnet, netInUse.schema_bbdd, selectedNet.nivel1_id, selectedNet.nivel2_id, selectedNet.nivel3_id, selectedNet.nivel4_id).subscribe(
      (res) => {
        if (res['mapIdList'].length == 0) {
          this.toastr.info(
            this.translateService.instant('NETWORK_QUERY.UNNASIGN_TERRITORY'),undefined, {
              positionClass: 'toast-top-center'
            }
          );
          // this.closeEvent.emit();
          this.dataLoadingService.closeDataLoadingDialog();

        } else {
          // Se vuelve a comprobar si hay territorios vacíos para mostrar el mensaje debido al bucle
          if (res['mapIdList'].length == 0) {
            this.toastr.info(
              this.translateService.instant('NETWORK_QUERY.UNNASIGN_TERRITORY'),undefined, {
                positionClass: 'toast-top-center'
              }
            );
          }   
        let obj = {
          elements: [],
          labelName: selectedNet.nombre,
          labelCoordenates: [res['labelCoordenates'][0]]
        }
        res['mapIdList'].forEach(cpost => {
          obj.elements.push(cpost.elements[0]);
        });
        this.objGroups.groups.push(obj);
        this.addFillLayerGroupedByZipCode(this.objGroups, selectedNet.nombre);
        // this.closeEvent.emit();
        this.dataLoadingService.closeDataLoadingDialog();

        }
      }
    )


  }

  private clickEvent(e, groupName, sourceLayer, idAdd?): void {
    const groupEvent = this.isEventGroup(groupName);
    if (groupEvent !== null || groupEvent !== undefined) {
      if (groupEvent['properties']['events']) { // Comprobamos que están activos los eventos en la capa
        const features = this.map.queryRenderedFeatures(e.point, {
          layers: groupName['layers']
        });
        if (features.length) {
          let found = false;
          const featureInfo = this.getFeatureType(features);
          const objToSend = {
            minutes: this.selectedTimer,
            country_map: this.userService.getLanguageRole(),
            mapId: featureInfo['properties'][this.getTypeByCountry()]
          };
          this.mapIdSelected = featureInfo['properties'][this.getTypeByCountry()];
          const lngLat = e['lngLat'];
          this.clickEvenEmit.emit(objToSend);

        }
      }
    }
  }


  public addFillLayerGroupedByZipCode(data: any, selectedLevel: string): void {
    this.dataArray = data['groups'];
    this.resetMap();
    setTimeout(() => {
      let featureCollection = {
        type: 'FeatureCollection',
        features: []
      };
      if (data && data['groups'] && data['groups'].length > 0 && this.map !== undefined) {
        const sourceAdd = selectedLevel;
        const groupAdd = selectedLevel;
        if (this.map.getSource(sourceAdd) === undefined) {
          this.map.addSource(sourceAdd, {
            type: 'vector',
            url: this.getSourceByCountry()
          });
          this.addSource(sourceAdd);
        } else {
          if (_.findIndex(this.dataMap, ['sourceName', sourceAdd]) === -1) {
            this.addSource(sourceAdd);
          }
        }
        const indexSource = _.findIndex(this.dataMap, ['sourceName', sourceAdd]);

        if (_.findIndex(this.dataMap[indexSource]['groups'], function (group) { return group['nameGroup'] == groupAdd; }) === -1) {
          this.addGroup(groupAdd, sourceAdd, 'fill', '');
        }

        const colorsArray = this.generateRandomColors(data['groups'].length);
        _.forEach(data['groups'], (group, i) => {
          const datosJson = [
            'all',
            [
              'match',
              ['get', this.getTypeByCountry()],
              group['elements'],
              true,
              false,
            ],
          ];
          featureCollection = this.generateLabelCoordenates(group['labelCoordenates'], group['labelName'], featureCollection);
          const paint =
          {
            'fill-color': colorsArray[i],
            'fill-opacity': [
              'case',
              ['boolean', ['feature-state', 'hover'], false],
              1,
              0.8,
            ],
            'fill-outline-color': this.tema.getProperty('--map-outline-color'),
          };
          this.addLayerTypeFill(
            environment.map.typesLayers.pos4Fill + '_' + i,
            sourceAdd,
            this.getLayerByCountry(),
            groupAdd,
            datosJson,
            paint
          );
        });
        this.activeSource = this.sourceCpos;
      }
    }, 500);
  }

  private addLayerTypeFill(
    idAdd: string,
    sourceAdd: string,
    sourceLayer: string,
    groupedName: string,
    filterAdd: any,
    paintAdd: any
  ) {
    if (this.map.getLayer(idAdd) !== undefined) {
      this.map.off("click", idAdd, (e) => {
        this.clickEvent(e, groupedName, sourceAdd);
      });
      this.map.off("mousemove", idAdd, (e) =>
        this.mouseMove(e, sourceAdd, sourceLayer, idAdd)
      );
      this.map.off("mouseleave", idAdd, (e) =>
        this.mouseLeave(e, sourceAdd, sourceLayer, idAdd)
      );
      this.map.removeLayer(idAdd);
    } else {
      if (this.map.getSource(sourceAdd) !== undefined) {
        this.map.addLayer(
          {
            id: idAdd,
            type: "fill",
            source: sourceAdd,
            "source-layer": sourceLayer,
            paint: paintAdd,
            filter: filterAdd,
          }
        );
        this.addDataLayer(idAdd, groupedName, sourceAdd);
        this.map.on("mousemove", idAdd, (e) => {
          this.mouseMove(e, sourceAdd, sourceLayer, idAdd);
        });
        this.map.on("mouseleave", idAdd, (e) => {
          this.mouseLeave(e, sourceAdd, sourceLayer, idAdd);
        });
        this.map.on("click", idAdd, (e) => {
          this.clickEvent(e, groupedName, sourceAdd, idAdd);
        });
      }
    }
  }

  private generateLabelCoordenates(labelCoordenates: object[], labelName: string, featureCollection: object): any {
    let featureItem;
    _.forEach(labelCoordenates, (coordinate: object): void => {
      featureItem = {
        type: 'Feature',
        geometry: {
          type: 'Point',
          coordinates: [coordinate['longitude'] ? coordinate['longitude'] : coordinate['x'],
          coordinate['latitude'] ? coordinate['latitude'] : coordinate['y']]
        },
        properties: {
          name: labelName
        }
      };
      featureCollection['features'].push(featureItem);
    });
    return featureCollection;
  }


  private mouseMove(
    e: mapboxgl.EventData,
    mySource: string,
    mySourceLayer: string,
    layerId: string
  ) {
    if (this.hoveredStateId !== null) {
      this.map.setFeatureState(
        {
          source: mySource,
          sourceLayer: mySourceLayer,
          id: this.hoveredStateId,
        },
        { hover: false }
      );
    }
    this.hoveredStateId = e.features[0].id;
    this.map.setFeatureState(
      {
        source: mySource,
        sourceLayer: mySourceLayer,
        id: this.hoveredStateId,
      },
      { hover: true }
    );
    if (e.features[0]) {
      this.map.getCanvas().style.cursor = "pointer";
      const textToShow = this.getTextToShow(e.features[0]);
      const description = "<div>" + textToShow + "</div>";
      e.point.y = e.point.y - 10;
      this.popup
        .setLngLat(this.map.unproject(e.point))
        .setHTML(description)
        .addTo(this.map);
    }
  }

  private getTextToShow(features: any) {
    let textToReturn = "";
    if (this.userService.getLanguageRole() === 'ES') {
      const featureProp = features["properties"];
      if (featureProp['COD_POSTAL'] !== undefined) {
        textToReturn = featureProp['COD_POSTAL'];
      } else if (featureProp['CODMUN'] !== undefined) {
        textToReturn = featureProp['CODMUN'] + '- ' + featureProp['Municipio'];
      } else if (featureProp['CODPROV'] !== undefined) {
        textToReturn = featureProp['CODPROV'] + '- ' + featureProp['Nombre'];
      }
    } else if (this.userService.getLanguageRole() === 'DE') {
      const featureProp = features["properties"];
      if (featureProp['Stab_nr'] !== undefined) {
        textToReturn = featureProp['Stab_nr'] + "-" +
          featureProp["LAU_LEV2_T"];;
      } else if (featureProp['GEN'] !== undefined) {
        textToReturn = featureProp['GEN'];
      }
    }
    return textToReturn;
  }

  private mouseLeave(
    e: mapboxgl.EventData,
    mySource: string,
    mySourceLayer: string,
    layerId: string
  ) {
    if (this.hoveredStateId !== null) {
      this.map.setFeatureState(
        {
          source: mySource,
          sourceLayer: mySourceLayer,
          id: this.hoveredStateId,
        },
        { hover: false }
      );
    }
    this.hoveredStateId = null;
    this.popup.remove();
    this.hoverIds = [];
  }

  public addSource(sourceName: string) {
    const sourceObj: sourceMap = {
      sourceName: sourceName,
      groups: []
    };
    this.dataMap.push(sourceObj);
  }

  public addGroup(groupName: string, sourceName: string, type: string, color: string) {
    const indexSource = _.findIndex(this.dataMap, ['sourceName', sourceName]);
    const indexGroup = _.findIndex(this.dataMap[indexSource]['groups'], ['groupName', groupName]);
    if (indexGroup >= 0) { // El grupo no existe y lo creamos
      this.removeLayerLegend(this.dataMap[indexSource], this.dataMap[indexSource]['groups'][indexGroup], true);
      if (indexSource >= 0) {
        const groupAdd: groupMap = {
          groupName: groupName,
          type: type,
          color: color,
          border: false,
          layers: [],
          labels: this.extractLabels(),
          markers: [],
          properties: {
            visibility: 'visible',
            events: false,
            showLabels: false
          }
        };
        this.dataMap[indexSource]['groups'].push(groupAdd);
      }
    } else if (indexSource >= 0) {
      const groupAdd: groupMap = {
        groupName: groupName,
        type: type,
        color: color,
        border: false,
        layers: [],
        labels: this.extractLabels(),
        markers: [],
        properties: {
          visibility: 'visible',
          events: false,
          showLabels: false
        }
      };
      this.dataMap[indexSource]['groups'].push(groupAdd);
    }
  }

  public extractLabels() {
    const toReturn = [];
    _.forEach(this.dataArray, obj => {
      if (obj['labelCoordenates'] !== null) {
        const objLabel = {
          labelName: obj['labelName'],
          labelCoordenates: { x: obj['labelCoordenates'][0]['x'], y: obj['labelCoordenates'][0]['y'] }
        };
        toReturn.push(objLabel);
      }
    });
    return toReturn;
  }

  private addDataLayer(nameLayer: string, nameGroup: string, nameSource: string) {
    const indexSource = _.findIndex(this.dataMap, ['sourceName', nameSource]);
    if (indexSource >= 0) {
      const indexGroup = _.findIndex(this.dataMap[indexSource]['groups'], ['groupName', nameGroup]);
      if (indexGroup >= 0) {
        const layerObj = {
          layerName: nameLayer,
          order: 0,
          type: "fill",
          color: '',
          clicks: [],
        };
        this.dataMap[indexSource]['groups'][indexGroup]['layers'].push(layerObj);
      }
    }
  }

  private extractBoundaries(data: any) {
    const objToReturn = {
      type: 'Feature',
      geometry: {
        type: 'MultiPolygon',
        coordinates: data['groups']['boundaries'][0]['coordinates']
      }
    };
    return objToReturn;
  }

  public changeBorderColorMap(source: sourceMap, group: groupMap) {
    const dialogConfig = new MatDialogConfig();
    dialogConfig.disableClose = true;
    dialogConfig.autoFocus = true;
    dialogConfig.data = {
      color: group["color"],
    };
    const dialogRef = this.dialog.open(ColorPickerModalComponent, dialogConfig);
    dialogRef.afterClosed().subscribe((result) => {
      if (result) {
        group["color"] = result;
        if (group["type"] === "border") {
          this.map.setPaintProperty(group["groupName"], "line-color", result);
        } else if (group["type"] === "border-map") {
          this.map.setPaintProperty(group["groupName"], "fill-outline-color", result);
        }
      }
      this.removeGroupedStuffs(group);
    });
  }

  private removeGroupedStuffs(group: any) {
    if (group !== undefined && group["markers"].length > 0) {
      _.forEach(group["markers"], (marker) => {
        marker.remove();
      });
    }
  }

  public changeLayerProperties(source: any, group: any, property: string, value: any) {
    if (property === "visibility") {
      _.forEach(group["layers"], (layer) => {
        this.map.setLayoutProperty(layer["layerName"], property, value);
      });
      group["properties"][property] = value;
    } else if (property === "showLabels") {
      if (group['type'] === 'fill') {
        group["properties"][property] = !value;
        this.createMarkers(group, !value);
      }
    } else if (property === "events") {
      _.forEach(this.dataMap, source => {
        _.forEach(source['groups'], groupEach => {
          if (groupEach['groupName'] === group['groupName']) {
            group["properties"][property] = true;
          } else {
            groupEach["properties"][property] = false;
          }
        });
      });
    } else if (property === 'line-width') {
      let valueBorder = 1;
      if (!value) {
        valueBorder = 3;
      }
      _.forEach(group['layers'], layer => {
        this.map.setPaintProperty(layer['layerName'], 'line-width', valueBorder);
      });
      group['border'] = !value;
    }
  }

  public isDataMapEmpty() {
    let toReturn = true;
    if (this.dataMap.length !== 0) {
      _.forEach(this.dataMap, (source) => {
        if (source['groups'].length !== 0) {
          toReturn = false;
        }
      });
    }
    return toReturn;
  }

  public resetMap(): void {
    if (!this.isDataMapEmpty()) {
      _.forEach(this.dataMap, (source, index) => {
        if (source["groups"] !== undefined) {
          if (source["groups"].length > 0) {
            _.forEach(source["groups"], (group) => {
              this.removeLayerLegend(source, group, false);
            });
          }   
        }
        if (this.dataMap.length === (index + 1)) {
          this.dataMap = [];
        }
      });
      this.rangeArray = [];
      this.clickedElements = [];
      // this.marker.remove();
    }
  }

  public resetDataGrid(): void {
    this.selectedTerrDataSource = [];
  }

  public removeLayerLegend(source: any, group: any, isLayer: boolean): void {
    if (group['type'] === 'border' || group['type'] === 'border-map') {
      _.forEach(group['layers'], (layer, indexLayer) => {
          this.map.removeLayer(layer['layerName']);
        if ((indexLayer + 1) === group['layers'].length) {
          source['groups'] = [];
        }
        if (source['groups'].length === 0) {
          this.map.removeSource(source['sourceName']);
          if (isLayer) {
            _.remove(this.dataMap, function(sourceMap) {return sourceMap['sourceName'] === source['sourceName'];});
          }
        }
      });
    } else {
      _.forEach(group['layers'], (layer, indexLayer) => {
        if (layer['clicks'].length !== 0) { // Primero eliminamos los clicks de la capa
          _.forEach(layer['clicks'], (click: object, indexClick): void => {
            this.map.setFeatureState({
              source: this.sourceCpos,
              sourceLayer: this.getLayerByCountry(),
              id: click['id']
            }, {
              clicked: 0
            });
            if ((indexClick + 1) === layer['clicks'].length) {  
              this.map.off('click', layer['layerName']);
              this.map.removeLayer(layer['layerName']);
            }
          });
        } else { // No hay click y eliminamos la capa
          this.map.removeLayer(layer['layerName']);
        }
        if ((indexLayer + 1) === group['layers'].length) {
          source['groups'] = [];
          this.rankLegend = [];
        }
      });
      // this.marker.remove();
    }
  }

  private removeMarkers(group: groupMap) {
    if (group["markers"].length > 0) {
      _.forEach(group["markers"], (marker, i) => {
        marker.remove();
        if (group["markers"].length === i + 1) {
          group["markers"] = [];
        }
      });
    }
  }


  public removeSelectedElements(): void {
    _.forEach(this.clickedElements, (item: object): void => {
      this.map.setFeatureState({
        source: this.sourceCpos,
        sourceLayer: this.getLayerByCountry(),
        id: item['id']
      }, {
        clicked: 0
      });
    });
    this.clickedElements = [];
  }

  public exportToImage(): void {
    const currentDate = new Date();
    const fileName =
      "Map_" +
      this.formatData(currentDate.getDate()) +
      "_" +
      this.formatData(currentDate.getMonth() + 1) +
      "_" +
      currentDate.getFullYear() +
      "_" +
      this.formatData(currentDate.getHours()) +
      "_" +
      this.formatData(currentDate.getMinutes()) +
      "_" +
      this.formatData(currentDate.getSeconds());
    const element = document.querySelector('.mapboxgl-control-container');
    element.setAttribute('style', 'visibility: hidden');
    setTimeout(() => {
      html2canvas(document.getElementById("network-query-map")).then((canvas) => {
        const imgData = canvas.toDataURL("image/png");
        const downloadLink = document.createElement("a");
        downloadLink.href = imgData;
        downloadLink.download = fileName;
        downloadLink.click();
        this.hasRemovedLayer.emit(environment.map.exportToImage);
        this.showExportSpinner = false;
        element.setAttribute('style', 'visibility: visible');
      });
    }, 200);
  }

  private formatData(data: number): string {
    return data < 10 ? "0" + data : data.toString();
  }

  public removeSelectedElement(cp: string): void {
    if (this.clickedElements && this.clickedElements.length && cp) {
      const itemToRemove = _.find(this.clickedElements, { cp });
      if (_.get(itemToRemove, "id")) {
        this.map.setFeatureState(
          {
            source: this.sourceCpos,
            sourceLayer: this.getLayerByCountry(),
            id: itemToRemove["id"],
          },
          {
            clicked: 0,
          }
        );
        _.remove(this.clickedElements, { id: itemToRemove["id"] });
      }
    }
  }

  public getSourceByCountry() {
    let toReturn = environment.map.urlBoundariesCP.source;
    if (this.userService.getLanguageRole() === "DE") {
      toReturn = environment.map.urlBoundariesGermanyCP.source;
    }
    return toReturn;
  }

  public getLayerByCountry() {
    let toReturn = environment.map.urlBoundariesCP.layer;
    if (this.userService.getLanguageRole() === "DE") {
      toReturn = environment.map.urlBoundariesGermanyCP.layer;
    }
    return toReturn;
  }

  private getTypeByCountry() {
    let toReturn = "COD_POSTAL";
    if (this.userService.getLanguageRole() === "DE") {
      toReturn = "Stab_nr";
    }
    return toReturn;
  }

  private getLngMap() {
    let centerArray = environment.map.lng;
    if (this.userService.getLanguageRole() === "DE") {
      centerArray = 10.451526;
    }
    return centerArray;
  }

  private getLatMap() {
    let centerArray = environment.map.lat;
    if (this.userService.getLanguageRole() === "DE") {
      centerArray = 51.165691;
    }
    return centerArray;
  }

  private getArrayFeatures(arrayMarkers: any) {
    const featuresArray = [];
    _.forEach(arrayMarkers, (marker) => {
      const feature = {
        'type': 'Feature',
        'geometry': {
          'type': 'Point',
          'coordinates': [marker['longitude'], marker['latitude']]
        }
      }
      featuresArray.push(feature);
    });
    return featuresArray;
  }

  private initialDataLoad(): void {
    this.legendLayerTitle = this.translate.instant('LEGEND_MAP.TITLE');
    this.markerColorAux = _.clone(this.markerColorsAvailable);
    this.territoriesColorsAux = _.clone(this.territoriesColorsAvailable);
    this.borderColors = {
      [this.sourceProv]: 'blue',
      [this.sourceMuni]: 'grey',
      [this.sourceCpos]: environment.map.defaultColorMarker
    };
    const arraySubscriptions = [];
    this.mapService.getUserPalettes().subscribe(res => {
      this.modalColors = res && res['colorsPalette'] ? res['colorsPalette'] : [];
    });
    this.loadMap();
  }


  private showMakerInMap(item: object, isList: boolean, color: string): mapboxgl.Marker {
    const lngLat = new mapboxgl.LngLat(item['longitude'], item['latitude']);
    const marker = new mapboxgl.Marker({
      color,
      scale: 0.5 // Para cambiar el tamaño del marker 0 a 1
    })
      .setLngLat(lngLat)
      .addTo(this.map);
    marker.getElement().addEventListener('click', (e) => {
      e.stopPropagation();
      if (e.ctrlKey || e.metaKey) {
        marker.remove();
        if (isList) {
          const deletedMarker = _.remove(this.markersList, (itemMarker) => {
            return itemMarker['marker'] === marker;
          });
          const index = _.findIndex(this.markersList, (element: object) => {
            return element['name'] === deletedMarker[0]['name'];
          });
          if (index === -1) {
            const layerRemoved = _.remove(this.layersLegend, (layer: object) => {
              return layer['type'] === environment.map.typesLayers.genericMarker &&
                layer['name'] === deletedMarker[0]['name'];
            });
            this.markerColorAux.push(layerRemoved[0]['color']);
            this.hasRemovedLayer.emit(deletedMarker[0]['name']);
          }
        } else {
          this.geoCoder.clear();
          _.remove(this.layersLegend, (layer: object) => {
            return layer['type'] === environment.map.typesLayers.findMarker &&
              layer['lat'] === marker.getLngLat().lat &&
              layer['lng'] === marker.getLngLat().lng;
          });
        }
      }
    }
    );
    return marker;
  }

  public findByCpOrMunicipality(item: object): void {
    if (item["latitude"] && item["longitude"]) {
      const marker = this.showMakerInMap(item, false, this.colorMarker);
      this.findByCpMarkers.push(marker);
      this.layersLegend.push({
        name: this.translateService.instant(environment.map.layersName.findMarker) + "(" + item["name"] + ")",
        type: environment.map.typesLayers.findMarker,
        lat: marker.getLngLat().lat,
        lng: marker.getLngLat().lng,
        color: this.colorMarker,
      });
      this.map.flyTo({
        center: [item["longitude"], item["latitude"]],
        zoom: 9,
        essential: true
      });
    }
  }

  public changeMap() {
    this.map.flyTo({
      center: [this.getLngMap(), this.getLatMap()]
    });

    const language = this.userData["language_user"].substring(0, 2);
    this.map.setLayoutProperty("country-label", "text-field", [
      "get",
      "name_" + language,
    ]);
    this.map.setLayoutProperty("state-label", "text-field", [
      "get",
      "name_" + language,
    ]);
    this.map.setLayoutProperty("settlement-major-label", "text-field", [
      "get",
      "name_" + language,
    ]);
    this.map.setLayoutProperty("settlement-minor-label", "text-field", [
      "get",
      "name_" + language,
    ]);
  }

  public loadMap(): void {
    this.map = new mapboxgl.Map({
      accessToken: environment.map.mapBoxToken,
      container: "network-query-map",
      style: this.tema.getProperty("--mapa"),
      center: [this.getLngMap(), this.getLatMap()],
      zoom: environment.map.zoom,
      preserveDrawingBuffer: true,
      attributionControl: false,
    });
    this.popup = new mapboxgl.Popup({
      closeButton: false,
      closeOnClick: false,
    });
    this.popupPin = new mapboxgl.Popup({
      closeButton: false,
      closeOnClick: true,
    });
    // language control
    const language = this.userData["language_user"].substring(0, 2);
    this.map.addControl(
      new MapboxLanguage({
        defaultLanguage: language,
      })
    );
    // zoom control
    this.map.addControl(
      new mapboxgl.NavigationControl({
        showCompass: false,
        showZoom: true,
        visualizePitch: false,
      })
    );
    this.geoCoder = new MapboxGeocoder({
      accessToken: environment.map.mapBoxToken,
      mapboxgl: this.map,
      flyTo: false,
      marker: false,
      placeholder: this.translateService.instant("BUTTON.SEARCH"),
      language,
    });
    this.map.addControl(this.geoCoder, "top-left");
    this.geoCoder.on("result", (ev) => {
      const item = {
        longitude: ev["result"]["center"][0],
        latitude: ev["result"]["center"][1],
        name: ev["result"]["text"],
      };
      this.findByCpOrMunicipality(item);
    });
    document
      .querySelector(".mapboxgl-ctrl-zoom-in")
      .setAttribute("title", "Zoom");
    document
      .querySelector(".mapboxgl-ctrl-zoom-out")
      .setAttribute("title", "Zoom");
    this.map.on("load", () => {
      this.map.setLayoutProperty("country-label", "text-field", [
        "get",
        "name_" + language,
      ]);
      this.map.setLayoutProperty("state-label", "text-field", [
        "get",
        "name_" + language,
      ]);
      this.map.setLayoutProperty("settlement-major-label", "text-field", [
        "get",
        "name_" + language,
      ]);
      this.map.setLayoutProperty("settlement-minor-label", "text-field", [
        "get",
        "name_" + language,
      ]);
    });
  }

  ngAfterViewChecked() {
    const idMap = jQuery('#network-query-map');
    if (idMap.length !== 0 && !this.isInit) {
      this.isInit = true;
      this.userData = this.userService.getCurrentUser();
      this.initialDataLoad();
    }
  }


  public changeGridDatabaseBtnTooltip() {
    this.showGridDatabase = !this.showGridDatabase;
  }

  dxgridDatabaseOnExporting(e) {
    const workbook = new Workbook();
    const worksheet = workbook.addWorksheet('Employees');

    exportDataGrid({
      component: e.component,
      worksheet,
      autoFilterEnabled: true,
    }).then(() => {
      workbook.xlsx.writeBuffer().then((buffer) => {
        saveAs(new Blob([buffer], { type: 'application/octet-stream' }), 'DataGrid.xlsx');
      });
    });
    e.cancel = true;
  }


  @HostListener('document:mousemove', ['$event'])
  onMouseMove(event: MouseEvent) {
    if (!this.grabber) {
        return;
    }
    this.resizer(event.clientY - this.oldY);
    this.oldY = event.clientY;
  }

  @HostListener('document:mouseup', ['$event'])
  onMouseUp(event: MouseEvent) {
    this.grabber = false;
  }

  resizer(offsetY: number) {    
    if (this.gridDataBaseheight <= 800 ){
      this.gridDataBaseheight -= offsetY;
    }
    else {
      this.gridDataBaseheight -= 1;
    }    
  }


  @HostListener('document:mousedown', ['$event'])
  onMouseDown(event: MouseEvent) {
    let target = (<HTMLElement>event.target).id;    
    if (target=="grabber"){      
      this.grabber = true;
      this.oldY = event.clientY;
    }    
  }

  ngOnInit(): void {
  }

}