0

I have an arcGIS map in angular 10. The polygon is plotting on the map based on the wkid and the projected ring values. I need to re draw the polygon when click on the map. click event collect the ID from the map with the hottest() and I need to redraw the polygon. I am using 'hitself.router.navigateByUrl(dashurl);' to reload the page to show the updated polygon. But the polygon not drawing on the map corresponding to the id retrieved. I found the value of the wkid and the rings are not updating properly. Am I doing anything wrong? Please find my code below.

import {
  Component,
  OnInit,
  ViewChild,
  ElementRef,
  Input,
  Output,
  EventEmitter,
  OnDestroy,
  NgZone
} from '@angular/core';

import { HttpClient, HttpHeaders } from '@angular/common/http';
import { GisService } from '../shared/service/gis.service';
import { ActivatedRoute, Router } from '@angular/router';
import { map } from 'rxjs/operators';
import { loadScript, loadModules } from 'esri-loader';
import esri = __esri; // Esri TypeScript Types
import { empty } from 'rxjs';
import { AppConfig } from '../shared/config/app.config';

@Component({
  selector: 'app-esri-map',
  templateUrl: './esri-map.component.html',
  styleUrls: ['./esri-map.component.css'],
})
export class EsriMapComponent implements OnInit, OnDestroy {
  @Output() mapLoadedEvent = new EventEmitter<boolean>();
  @ViewChild('mapViewNode', { static: true }) private mapViewEl: ElementRef;
  view: any;
  dynamicRings: any;
  wkid: any;
  id: any;
  loadingmap = true;
  // to keep loaded esri modules
  esriModules = {
    graphic: null,
    geometry: {
      Polygon: null,
      SpatialReference: null,
      support: { webMercatorUtils: null },
    },
    tasks: {
      GeometryService: null,
      support: { ProjectParameters: null },
    },
  };

  private _zoom = 20;
  private _basemap = 'hybrid';
  private _loaded = false;
  private _view: esri.MapView = null;
  private _nextBasemap = 'streets';
  public _selectedLayer: Array<string>;

  public layersMapIdxArray: string[] = ['0', '1', '2'];
  public mapalllayerview: boolean;
  public layersDic = {};

  private readonly esriMapUri: string;

  get mapLoaded(): boolean {
    return this._loaded;
  }

  

  public onLayerChange(val: Array<string>) {
    console.log(val);
    // hide all the layers before ahowing the selected layers
    for (const al of this.layersMapIdxArray) {
      this.layersDic[al].visible = false;
    }

    // this.mapalllayerview = false;

    this._selectedLayer = val;
    // Add the layer 15 to get the ID eve all other layers are disabled.
    if (this._selectedLayer.indexOf("15") === -1) {
      this._selectedLayer.push('15');
    }
    for (const v of val) {
      this.layersDic[v].visible = true;
    }
  }

  constructor(
    private gisService: GisService,
    private http: HttpClient,
    private route: ActivatedRoute,
    private router: Router,
    private zone: NgZone,
    private appConfig: AppConfig) {
  }

  async initializeMap() {
    try {
      loadScript();
      // Load the modules for the ArcGIS API for JavaScript
      const [
        EsriMap,
        EsriMapView,
        Polygon,
        SpatialReference,
        webMercatorUtils,
        GeometryService,
        ProjectParameters,
        FeatureLayer,
        BasemapToggle,
        BasemapGallery,
        Graphic,
      ] = await loadModules([
        'esri/Map',
        'esri/views/MapView',
        'esri/geometry/Polygon',
        'esri/geometry/SpatialReference',
        'esri/geometry/support/webMercatorUtils',
        'esri/tasks/GeometryService',
        'esri/tasks/support/ProjectParameters',
        'esri/layers/FeatureLayer',
        'esri/widgets/BasemapToggle',
        'esri/widgets/BasemapGallery',
        'esri/Graphic',
      ]);

      // save the modules on a property for later
      this.esriModules.geometry.Polygon = Polygon;
      this.esriModules.geometry.SpatialReference = SpatialReference;
      this.esriModules.geometry.support.webMercatorUtils = webMercatorUtils;
      this.esriModules.tasks.GeometryService = GeometryService;
      this.esriModules.tasks.support.ProjectParameters = ProjectParameters;
      this.esriModules.graphic = Graphic;

      // Configure the Map
      const mapProperties: esri.MapProperties = {
        basemap: this._basemap,
      };

      const map: esri.Map = new EsriMap(mapProperties);

      // Initialize the MapView
      const mapViewProperties: esri.MapViewProperties = {
        container: this.mapViewEl.nativeElement,
        // center: this._center,
        zoom: this._zoom,
        map: map,
      };

      this._view = new EsriMapView(mapViewProperties);

      // Add layers to the map according to the selection

      // The layer 15 will be the stack at the top of the layers so 15 will be consider first.I c
      this.layersMapIdxArray.push('15');
      console.log(this.layersMapIdxArray);
      for (const idx of this.layersMapIdxArray) {
        this.layersDic[idx] = new FeatureLayer({
          url: `${this.esriMapUri}/${idx}`,
          visible: this.mapalllayerview,
          outFields: ['*'],
        });
        map.add(this.layersDic[idx]);
      }

      // Basemap toglle section
      var basemapToggle = new BasemapToggle({
        view: this._view,
        nextBasemap: this._nextBasemap,
      });
      this._view.ui.add(basemapToggle, 'bottom-right');

      // Load details of ID when click on the map
      let hitself = this;
      this._view.on('click', function (event) {
        hitself._view
          .hitTest(event, { exclude: hitself._view.graphics })
          .then(function (response) {
            console.log(response);
            if (
              typeof response.results !== 'undefined' &&
              response.results.length > 0
            ) {
              var graphic = response.results[0].graphic;
              var attributes = graphic.attributes;
              var category = attributes.ID;
              var wind = attributes.ADDRESS;
              var name = attributes.ADDRESS;
              hitself.id = category;
              var dashurl = 'dashboard/' + hitself.id;
              hitself.zone.run(() => {
                hitself.router.navigateByUrl(dashurl);
              });

            }
          });

        return;

      });

      await this._view.when(); // wait for map to load
      return this._view;
    } catch (error) {
      console.error('EsriLoader: ', error);
    }
  }

  // point geometry extent is null
  zoomToGeometry(geom) {
    console.log(`Original Geometry: ${JSON.stringify(geom.toJSON())}`);

    const geomSer = new this.esriModules.tasks.GeometryService(
      'http://sampleserver6.arcgisonline.com/arcgis/rest/services/Utilities/Geometry/GeometryServer'
    );

    const outSpatialReference = new this.esriModules.geometry.SpatialReference({
      wkid: 102100,
    });

    const params = new this.esriModules.tasks.support.ProjectParameters({
      geometries: [geom],
      outSpatialReference,
    });

    const self = this;

    geomSer
      .project(params)
      .then(function (result) {
        const projectedGeom = result[0];

        if (!projectedGeom) {
          return;
        }

        // console.log(
        //   `Projected Geometry: ${JSON.stringify(projectedGeom.toJSON())}`
        // );
        return projectedGeom;
      })
      .then(function (polly) {
        console.log(self.esriModules.graphic);
        self._view.graphics.add(
          new self.esriModules.graphic({
            geometry: polly,
            symbol: {
              type: 'simple-fill',
              style: 'solid',
              color: [255, 0, 0, 0.1],
              outline: {
                width: 2,
                color: [255, 0, 0, 1],
              },
            },
          })
        );

        self._view.extent = polly.extent.clone().expand(3);
      });
  }

  ngOnInit() {
    this.route.paramMap.subscribe((params) => {
      this.id = params.get('id');
      this.gisService.getidDetails(this.id).subscribe((posts) => {
        const get_wkid = posts[0]['spatialReference'];
        this.wkid = get_wkid['wkid'];
        const dynamicrings = posts[0]['features'];
        this.dynamicRings = dynamicrings[0]['geometry']['rings'];
      });

      this._selectedLayer = ['1', '0', '2'];
      // this.layersMapIdxArray = this._selectedLayer;
      this.mapalllayerview = true;

      this.initializeMap().then(() => {
        // The map has been initialized
        console.log('mapView ready: ', this._view.ready);
        const geom = new this.esriModules.geometry.Polygon({
          spatialReference: {
            wkid: this.wkid, //102704,
          },
          rings: this.dynamicRings,
        });

        this.zoomToGeometry(geom);
        console.log('mapView ready: ', this._view.ready);
        this._loaded = this._view.ready;
        this.mapLoadedEvent.emit(true);
        this.loadingmap = false;
      });
    });

  }

  ngOnDestroy() {
    if (this._view) {
      // destroy the map view
      this._view.container = null;
    }
  }
}
Adam-KER
  • 67
  • 9
  • Hi @adam-ker, I don't really understand why are you trying to update the page?, why not just draw the polygon? – cabesuon Oct 15 '20 at 17:36
  • Hi Cabesuon, there are a couple of components added on a single page. The map is a component. A unique 'id' is used to collect the details for all the components on the same page. The id can be available from the map also. When clicking on a point on the map, it collected the 'id' from the feature and use it to get the details from other API for the remaining components. Along with that, I have to draw the polygon according to the 'id'. ('id' will be passing to the API and it returns the WKID and rings, which passes to the 'zoomToGeometry()' to get the proper wkid then drawing the polygon.). – Adam-KER Oct 22 '20 at 06:35
  • My problem is, the polygon is drawing according to the past 'id' (Previous to previous 'id'). Not the id which passed now. any delay from the API response making the problem? – Adam-KER Oct 22 '20 at 06:39
  • I am getting the console, WebGL warning: drawArraysInstanced: Tex image TEXTURE_2D level 0 is incurring lazy initialization. – Adam-KER Oct 22 '20 at 09:58
  • Hi @adam-ker, sorry the delay .. I still don't really understand the issue, sorry .. Lets try to simplify it .. Wen the user click on the map, you want to retrieve the feature, use the id of the feature to get information from a service, and then with the information display it on the popup .. is that it? – cabesuon Oct 24 '20 at 19:32
  • Hi Cabesuon. I am facing this issue when I run in my local system. But on the server, it is working fine. I have to debug more into it to find out the reason it is not working only in localhost. Thanks for the response. – Adam-KER Nov 04 '20 at 13:53

0 Answers0