Get mapView in another Angular Component

121
1
11-19-2021 10:23 AM
matteorizzi
New Contributor II

Hello! Let me explain better my issue: 
- I created (in a typical way) a map View in the angular "component One":

 

export class MapComponent implements OnInit, OnDestroy {
  view: any;
  
  @ViewChild('esriMap', { static: true }) private mapViewEl!: ElementRef;

  initializeMap(): Promise<any> {
    const container = this.mapViewEl.nativeElement;
    esriConfig.portalUrl = "....";
    const webmap = new WebMap({
      portalItem: {
        id: '...',
      },
    });

    const layer = new FeatureLayer({
      // URL to the service
      URL: "..."
    });

    webmap.add(layer)

    const view = new MapView({
      container,
      map: webmap,
      zoom: 3,
      constraints: {
        minZoom: 3
      }
    });

    this.view = view;
    return this.view.when();
  }

 

 

Then I need to use the "goTo" method in another angular component, let's call it "component Two". 
How can I access the view defined in the component One from the component Two? Is it possible? 

Thank you so much

0 Kudos
1 Reply
ReneRubalcava
Frequent Contributor

You can move all the JSAPI logic into an injectable service and use that service in components you want to be able to access it.

 

import { Injectable } from '@angular/core';

import WebMap from '@arcgis/core/WebMap';
import MapView from '@arcgis/core/views/MapView';
import Bookmarks from '@arcgis/core/widgets/Bookmarks';
import Expand from '@arcgis/core/widgets/Expand';

@Injectable({
  providedIn: 'root'
})
export class MapService {
  public view: MapView | null = null;

  constructor() {}

  async createMap(container: HTMLDivElement) {
    const webmap = new WebMap({
      portalItem: {
        id: 'aa1d3f80270146208328cf66d022e09c'
      }
    });

    const view = new MapView({
      container,
      map: webmap
    });

    const bookmarks = new Bookmarks({
      view,
      // allows bookmarks to be added, edited, or deleted
      editingEnabled: true
    });

    const bkExpand = new Expand({
      view,
      content: bookmarks,
      expanded: true
    });

    // Add the widget to the top-right corner of the view
    view.ui.add(bkExpand, 'top-right');

    // bonus - how many bookmarks in the webmap?
    webmap.when(() => {
      if (webmap.bookmarks && webmap.bookmarks.length) {
        console.log('Bookmarks: ', webmap.bookmarks.length);
      } else {
        console.log('No bookmarks in this webmap.');
      }
    });

    this.view = view;
    return this.view.when();
  }
}
0 Kudos