Wywołanie funkcji dopiero po spełnieniu argumentu Angular Google Maps

0

Cześć.

Mam funkcje która liczy mi klientów narysowanej dookoła wielokąta. Tylko funkcja wykonuje się za każdym razem kiedy narysuję "kreskę" na mapie.
Funkcja działa bez problemów i liczy mi markery które są wewnątrz wielokąta (są w obszarze zaznaczenia). Funkcja ta niestety uruchamia się również dopiero po poruszeniu się(zmianie rozmiaru/elementu) mapy i dopiero wtedy przeliczy mi klientów. Ja chciałbym aby ta funkcja uruchamiała mi się dopiero wtedy gdy argument selectedArea będzie większy od 0 czyli będzie to oznaczało że wielokąt jest zamknięty. Chciałbym żeby funkcja uruchomiła się natychmiast i żeby od razu mi przeliczyła klientów bez konieczności ruszania myszką.

Oto mój kod TypeScript :

import { Component, EventEmitter, Input, OnInit, Output } from '@angular/core';
import { ClientService } from '../Services/ClientService';
import { Client } from '../Models/Client';
import { last } from 'rxjs/operators';
import { element } from 'protractor';
import { stringify } from '@angular/compiler/src/util';

@Component({
  selector: 'app-map',
  templateUrl: './map.component.html',
  styleUrls: ['./map.component.css']
})
export class MapComponent implements OnInit {
  title = 'WGCM';
  lat = 52.237049;
  lng = 18.517532;
  pointList: { lat: number; lng: number }[] = [];
  drawingManager;
  all_overlays = [];
  selectedShape: any;
  selectedArea = 0;


  @Input() clientList: Array<Client>;
  @Output() klienci : EventEmitter<Client[]> = new EventEmitter<Client[]>();
  clientLocations = [];
  circledClients = [];




  constructor(private client: ClientService){}

  ngOnInit(): void {
  }


  onMapReady(map) {
    this.initDrawingManager(map);
  }

  initDrawingManager = (map: any) => {
    const self = this;
    this.drawingManager = new google.maps.drawing.DrawingManager({
            drawingMode: google.maps.drawing.OverlayType.POLYGON,
            drawingControl: true,
            drawingControlOptions: {
              position: google.maps.ControlPosition.TOP_CENTER,
              drawingModes: [
                // google.maps.drawing.OverlayType.MARKER,
                google.maps.drawing.OverlayType.POLYGON,

              ],
            },
            markerOptions: {
              icon:
                "https://developers.google.com/maps/documentation/javascript/examples/full/images/beachflag.png",
            },
            circleOptions: {
              fillColor: "#ffff00",
              fillOpacity: 1,
              strokeWeight: 5,
              clickable: false,
              editable: true,
              zIndex: 1,
            },
          }
          );
    this.drawingManager.setMap(map);



    google.maps.event.addListener(
      this.drawingManager,
      'overlaycomplete',
      (event) => {
        if (event.type === google.maps.drawing.OverlayType.POLYGON) {
          const paths = event.overlay.getPaths();
          for (let p = 0; p < paths.getLength(); p++) {
            google.maps.event.addListener(
              paths.getAt(p),
              'set_at',
              () => {
                if (!event.overlay.drag) {
                  self.updatePointList(event.overlay.getPath());
                }
              }
            );
            google.maps.event.addListener(
              paths.getAt(p),
              'insert_at',
              () => {
                self.updatePointList(event.overlay.getPath());
              }
            );

            google.maps.event.addListener(
              paths.getAt(p),
              'remove_at',
              () => {
                self.updatePointList(event.overlay.getPath());
              }
            );
          }
          self.updatePointList(event.overlay.getPath());
          this.selectedShape = event.overlay;
          this.selectedShape.type = event.type;
        }
        if (event.type !== google.maps.drawing.OverlayType.MARKER) {
          // Switch back to non-drawing mode after drawing a shape.
          self.drawingManager.setDrawingMode(null);
          // To hide:
          self.drawingManager.setOptions({
            drawingControl: false,
          });
        }
      }
    );
  }

  private setCurrentPosition() {
    if ('geolocation' in navigator) {
      navigator.geolocation.getCurrentPosition((position) => {
        this.lat = position.coords.latitude;
        this.lng = position.coords.longitude;
      });
    }
  }

  deleteSelectedShape() {
    if (this.selectedShape) {
      this.selectedShape.setMap(null);
      this.selectedArea = 0;
      this.pointList = [];
      // To show:
      this.drawingManager.setOptions({
        drawingControl: true,
        drawingMode: google.maps.drawing.OverlayType.POLYGON
      });
    }
  }

  updatePointList(path) {
    this.pointList = [];
    const len = path.getLength();
    for (let i = 0; i < len; i++) {
      this.pointList.push(
        path.getAt(i).toJSON()
      );
    }
    this.selectedArea = google.maps.geometry.spherical.computeArea(
      path
    );
  }


  checkMarkersInBounds(event) {

    console.log("In method - testing");
    this.circledClients = [];


     this.clientLocations = this.getClientLocations();


    for(let company of this.clientLocations){

      let companyPosition = {Lat: company.latitude, Lng: company.longitude,latlng: new google.maps.LatLng(company.latitude,company.longitude)};


      if (this.selectedArea!=0) {
            let drawedPolygon = new google.maps.Polygon({ paths: this.pointList });


          const result = google.maps.geometry.poly.containsLocation
          (
            companyPosition.latlng,
            drawedPolygon
          )

          if (result) {
            this.circledClients.push(company);
          }

      }

      // console.log(this.circledClients);

    }
  }

  getClientLocations() : any[] {

    let cl = this.clientList.map(item => {
      const container = {};

      container['latitude'] = item.latitude;
      container['longitude'] = item.longitude;
      container['latlng'] = item.latitude+","+item.longitude;
      container['Nazwa'] = item.name;
      container['Miasto'] = item.city;

      return container;
  })

  return cl;
}


    }

Oraz mój kod HMTL :

<div class="map" *ngIf="clientList">
  <div>
    <button type="button" class="btn btn-dark" (click)="deleteSelectedShape()">Wyczyść rysowanie</button>
  </div>
  <div>
    <span> Selected Area: {{ selectedArea.toPrecision(5) }}m<sup>2</sup> </span>
    <span>Selected Clients : {{circledClients.length}}</span>
  </div>
  <agm-map class="map" [zoom] = "7" [latitude] ="lat" [longitude] ="lng"
    (mapReady)="onMapReady($event)"
    (boundsChange)="checkMarkersInBounds($event)"
    >
    <ng-container *ngFor= "let place of clientList">
      <agm-marker [latitude]= "place.latitude" [longitude]= "place.longitude"
      [title] ="place.name" [iconUrl] = getUrlMarker(place.segment)>
    <agm-info-window>
      <b>Kod klienta:</b> {{place.clientId}}
      <p><b>Nazwa:</b> {{place.name}}</p>
      <p><b>Miasto:</b> {{place.city}}</p>
      <p><b>Powiat:</b> {{place.province}}</p>
      <p><b>Segment:</b> {{place.segment}}</p>
    </agm-info-window>
    </agm-marker>
    </ng-container>
  </agm-map>


    <div *ngFor="let point of pointList">
      <div>{{ point.lat.toPrecision(5) }}, {{ point.lng.toPrecision(5) }}</div>
    </div>

</div>
0

Chciałbym żeby funkcja uruchomiła się natychmiast i żeby od razu mi przeliczyła klientów bez konieczności ruszania myszką.

jeśli na starcie masz już jakiś wielokąt narysowany no to uruchom ją w ngOnInit, albo ngAfterViewInit
po 2 sprawdź jakie eventy wystawia ci komponent agm-map być może masz już tam zdefiniowany taki event

0

Próbowałem z dragEnd w addEventListener ale nie chciało zadziałać. Może coś źle robiłem ale nie trybiło. Nic innego mi nie wpadło do głowy.

1 użytkowników online, w tym zalogowanych: 0, gości: 1