8.8.2 Integration with the Core API
8.8.2 Integration with the Core API jed124Map components can simplify the basics of app development, but at some point you’re likely to need the more fine-grained objects made available through the Core API we’ve been working with during the class. The Intro to map components (2D) sample provides a crosswalk of sorts for connecting map component code with Core API code. The first step is to obtain a reference to the Map’s DOM element:
const viewElement = document.querySelector("arcgis-map");
From there, you can set up a listener for when the Map is ready for interaction:
viewElement.addEventListener("arcgisViewReadyChange", (event) => {
console.log("Map component is ready", event);
});
Any code you want to build upon the map components can be embedded within this anonymous event listener.
Picking up where we left off, let’s add Penn State buildings (which we worked with in Lesson 1) to the map as a FeatureLayer. The first step will be to import that module.
- Add the following to the top of the script element that holds your JS code:
const [FeatureLayer] = await $arcgis.import( ["@arcgis/core/layers/FeatureLayer.js"] ); - Within the listener for the “arcgisViewReadyChange” event, instantiate a new FeatureLayer:
const buildingsLyr = new FeatureLayer({ url: "https://mapservices.pasda.psu.edu/server/rest/services/pasda/PSU_Campus/MapServer/1" });Creation of this FeatureLayer could also happen before getting the reference to the Map component. -
Finally, add the FeatureLayer to the map:
viewElement.map.add(buildingsLyr);
Note that while the arcgis-map element is referred to as a Map component, adding one to your page actually creates a MapView from the Core API. Thus, to add a layer, you need to access the Map associated with the MapView through its map property (viewElement.map). In this last step, you could certainly store a reference to the Map instead of chaining:
const map = viewElement.map;
map.add(buildingsLyr);
Finally, a side note on $arcgis.import()… We’ve implemented this function with arrays of modules/variables, but you should be aware that it can also be implemented without arrays. For example, in this little walkthrough in which FeatureLayer is the only Core API module being imported, we could do the import as follows instead:
const FeatureLayer = await $arcgis.import("@arcgis/core/layers/FeatureLayer.js");
You'll see single modules imported in this way in the documentation and I didn’t want the different syntax to throw you off.