ArcGIS Maps SDK for JavaScript Series 2: Understanding Map and MapView


In ArcGIS Maps SDK for JavaScript, Map and MapView are two important concepts used to create and display map applications.

Map

Map represents a map object that is the basis of map applications. Map can contain one or more layers, which can be base map layers, vector layers, raster layers, or any other type of layer. Map can also contain map symbolization (Symbology), labels, annotations and other information.

Sample code to create a Map object:

const map = new Map({
    
    
  basemap: 'streets-vector'
});

The code here creates a map object containing the 'streets-vector' basemap.

Common properties of Map

  1. allLayers(layers)
    • Type: Collection
    • Description: An expanded collection of all layers in the map (including basemaps)
  2. basemap
    • Type: String or Basemap object
    • Description: Specifies the basemap style of the map. It can be a predefined string (such as "streets", "satellite", "topo", etc.) or a custom Basemap object.
  3. ground
    • Type: Ground object
    • Description: A visualization for specifying the Earth's surface. The Ground object can set the type of ground, such as "world-elevation", "world-topobathymetry", etc.
  4. layers
    • Type: Layer collection
    • Description: Contains all layers on the current map. You can adjust the layer display on the map by adding or removing Layer objects, excluding the basemap.
// 创建一个具有默认底图的地图对象
const map = new Map({
    
    
  basemap: "streets"
});

// 添加一个图层到地图上
const layer = new TileLayer({
    
    
  url: "https://services.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer"
});
map.layers.add(layer);

// 创建一个地图视图
const mapView = new MapView({
    
    
  container: "viewDiv ",
  map: map,
  zoom: 10,
  center: [-122.4194, 37.7749]
});

The above code creates a map object with a "streets" basemap, then adds a tile layer, and finally uses a MapView to display the map in a specified HTML element.

Common methods of Map

  1. add(layer)(add layer)

    • Parameters: layer: Layer object
    • Description: Add the specified layer to the map. Layers can be added dynamically and displayed on the map through this method.
  2. remove(layer) (remove layer)

    • Parameters: layer: Layer object
    • Description: Removes the specified layer from the map. Use this method to remove layers from the map at runtime.
  3. findLayerById(id) (find layer by ID)

    • Parameter: id: String
    • Return value: Layer object
    • Description: Find and return the layer object on the map based on the specified ID.
  4. findLayersByName(name) (find layers based on name)

    • Parameters: name: String
    • Return value: Layer[] (layer array)
    • Description: Find and return an array of layer objects matching the name based on the specified name.
  5. removeAll() (remove all layers)

    • Description: Removes all layers from the map.
  6. destroy() (destroy the map)

    • Description: Destroy the map object and its related resources. Use this method to clean up the map object and free up memory, especially when the map is no longer needed.

MapView

MapView is a view component used to display Map objects. It is responsible for rendering the map onto the HTML page. MapView provides functions for users to interact with the map, such as panning, zooming, rotating and other operations. MapView also supports adding graphics and pop-up windows, and provides functions such as mouse events and interactive control.

Example code to create a MapView object:

const mapView = new MapView({
    
    
  container: 'viewDiv',
  map: map,
  zoom: 10,
  center: [longitude, latitude]
});

The code here creates a MapView object, renders it into the HTML element with the id 'viewDiv', and passes in the Map object created earlier. You can also set the initial zoom level and center coordinates.

Common properties of MapView

  1. container

    • Type: String or HTML element
    • Default: None
    • Description: Specifies the ID or actual HTML element of the HTML container element used to display the map. The map will be rendered in this container.
  2. map

    • Type: Map object
    • Default: None
    • Description: Specifies the map object, representing the map content of MapView.
  3. zoom (zoom level)

    • Type: Number
    • Default: None
    • Description: Specifies the initial zoom level of the map. You can set a number between the minimum zoom level and the maximum zoom level.
  4. center (center coordinate)

    • Type: Number[]
    • Default: None
    • Description: Specify the initial center point coordinates of the map. Expressed in the form of longitude and latitude, such as [longitude, latitude].
  5. rotation (rotation angle)

    • Type: Number
    • Default value: 0
    • Description: Specifies the initial rotation of the map, in degrees. You can set a number between -360 and 360.
  6. constraints (constraints)

    • Type: ViewpointConstraints object
    • Default: None
    • Description: It is used to set the constraints of the map, such as maximum zoom level, minimum zoom level, visible range, etc.

An example of creating a MapView object and configuring properties is as follows:

// 创建 Map 对象
const map = new Map({
    
    
  basemap: "streets"
});

// 创建 MapView 对象,并配置属性
const view = new MapView({
    
    
  container: "viewDiv", // 将地图渲染到指定的 HTML 元素中
  map: map, // 指定要显示的地图对象
  zoom: 10, // 设置初始缩放级别为 10
  center: [0, 0] // 设置初始中心点坐标为 [0, 0]
});

// 添加图层到地图
const layer = new TileLayer({
    
    
  url: "https://example.com/path/to/layer" // 设置图层的 URL
});
map.add(layer);

In the above code, a Map object is first created and the basemap to be used is specified. Then, a MapView object was created and the following properties were set in the configuration:

  • container: Specifies the ID of the HTML container element to render the map to or the actual HTML element ( mapContainerthe element with ID is used here).
  • map: Specify the map object to display, that is, the previously created Map object.
  • zoom: Set the initial zoom level to 10.
  • center:Set the initial center point coordinates to [0, 0].

Then, a layer object was created and added to the map.

Common methods of MapView

1. goTo() (jump)
jumps the view to the specified viewpoint. You can specify the viewpoint object to jump to, including zoom level, center point, rotation angle, etc. You can use the options parameter to specify jump options such as animation and duration.
MapView's goto method is a very practical method that allows us to switch the view to a specified position and zoom level.
Basic syntax of goto method:
goTo(target, options){[Promise]}
This method accepts two parameters:

  • target: The target location to view. It can be a Geometry (such as a point, line, or area), a Graphic (a shape on a map), or any object with location information.
  • options: Optional parameter used to specify view switching options, such as animation transition, zoom level, etc.

The goto method returns a Promise object that resolves after the view switch is completed. You can use the .then() method to handle operations after the view switching is completed.

Use the goto method to move the map view to a specified location and zoom:

const target = {
    
    
  target: [-118.80500, 34.02700], // 目标位置的经纬度坐标
  zoom: 13 // 缩放级别
};

view.goTo(target)
  .then(() => {
    
    
    // 视图切换完成后的操作
    console.log('视图已切换完成');
  })
  .catch((error) => {
    
    
    console.error('切换视图时发生错误', error);
  });

In the code above, we first create an object that contains target location and zoom level information. We then call view.goTo()the method, passing the object as parameter. After the view switching is completed, .then()the callback function in the method will be called, where you can perform operations after the view switching is completed. If an error occurs when switching views, .catch()the callback function in the method will be called, where the error condition can be handled.

It should be noted here that the goto method can also accept other options, such as animation transition time, rotation angle, etc. Can optionsbe configured in parameters. For detailed method and parameter descriptions, please refer to the official documentation of ArcGIS API for JavaScript.
2. on() (event monitoring)

  • Parameters: Object object
  • Description: Register to listen for map events.
    MapView's on method is an event listener that can be used to listen and process map events. MapView's on method returns a Promise object, and events can be handled by calling the object's then method.

on()Commonly used registration events for MapView methods are as follows:

  • "click": Fires when the user clicks on the map.
  • "double-click": Triggered when the user double-clicks on the map.
  • "drag": triggered when the user drags on the map.
  • "mouse-wheel": Fires when the user uses the mouse wheel on the map.
  • "pointer-down": Fires when the user presses any pointing device button (mouse button, touch screen, etc.) on the map.
  • "pointer-move": Triggered when the user moves any pointing device on the map.
  • "pointer-up": Fires when the user releases any pointing device button (mouse button, touch screen, etc.).

The sample code for using the on method is as follows:

<template>
  <div id="viewDiv"> 
  </div> 
</template>

<script setup> 
import {
    
     onMounted } from 'vue'
import Map from '@arcgis/core/Map.js';
import MapView from '@arcgis/core/views/MapView.js';


onMounted(()=>{
    
    
  initArcGisMap()
})

const initArcGisMap = () => {
    
    
  const map = new Map({
    
    
    basemap: "topo-vector"
  });

  const view = new MapView({
    
     
    zoom: 4,
    container: "viewDiv",
    map: map
  });
  view.ui.components = []; 

  const target = {
    
    
    target:[-118.80500, 34.02700],
    zoom:13
  }
 view.goTo(target)
  .then(()=>{
    
    
    // 视图切换完成后的操作
    console.log('视图已切换完成');
  })
  .catch((error)=>{
    
    
    console.error('切换视图时发生错误', error);
  })

  view.on('click', (event) => {
    
    
    // 处理点击事件
    console.log('click事件触发')
  })
  view.on('double-click', (event) => {
    
    
    // 处理双击事件
    console.log('double-click事件触发')
  });
  view.on('drag', (event) => {
    
    
    // 处理拖拽事件
    console.log('drag事件触发')
  });
  view.on('mouse-wheel', (event) => {
    
    
    // 处理鼠标滚轮事件
    console.log('mouse-wheel 事件触发')
  });
  view.on('pointer-down', (event) => {
    
    
    // 在地图上按下任意指针设备按钮(鼠标按钮、触摸屏等)时触发事件
    console.log('pointer-down 事件触发')
  });
  view.on('pointer-move', (event) => {
    
    
    // 在地图上移动任意指针设备时触发事件
    console.log('pointer-move 事件触发')
  });
  view.on('pointer-up', (event) => {
    
    
    // 释放任意指针设备按钮(鼠标按钮、触摸屏等)时触发事件
    console.log('pointer-up 事件触发')
  });
  view.on('extent-change', (event) => {
    
    
    // 地图视图的范围发生变化时触发事件
    console.log('extent-change 事件触发')
  });
}
</script>
<style scoped>  
#viewDiv {
    
    
  width: 100%;
  height: 100vh; 
}
</style>

3. The toMap() method
MapViewis toMap()used to convert the pixel coordinates on the page into the latitude and longitude coordinates on the map. It accepts an object containing the pixel coordinates on the page as a parameter and returns the corresponding latitude and longitude coordinates on the map.
Example using toMap() method:

<template>
  <div id="viewDiv">
  </div>
</template>

<script setup>
import { onMounted } from 'vue'
import Map from '@arcgis/core/Map.js';
import MapView from '@arcgis/core/views/MapView.js';  
let view
onMounted(() => {
  initArcGisMap()
})

const initArcGisMap = () => {
  const map = new Map({
    basemap: "topo-vector"
  });

  view = new MapView({
    center: [-118.80500, 34.02700],
    zoom: 4,
    container: "viewDiv",
    map: map
  });
  view.ui.components = [];

  view.on('click', handleMapClick)
}
  const handleMapClick = (event) => { 
    const screenPoint = {
        x: event.x,
        y: event.y
      }; 
    const mapPoint = view.toMap(screenPoint);
    console.log(`点击点的经纬度坐标为 经度:${mapPoint.latitude},纬度:${mapPoint.longitude}`)

  }
</script>
<style scoped>  #viewDiv {
    width: 100%;
    height: 100vh;
  }
</style> 

In the above code, the handleMapClick method is called when we click on the map. In this method, we obtain the pixel coordinates of the page clicked by the user through the event object. Then, use the view.toMap(screenPoint) method to convert the page pixel coordinates to the latitude and longitude coordinates on the map. Finally, print the obtained latitude and longitude values ​​to the console.
Run the code and you can see the latitude and longitude coordinates output by the console.
Insert image description here

4. The toScreen() method
MapViewis toScreen()used to convert the longitude and latitude coordinates on the map into pixel coordinates on the page. It accepts an object containing the latitude and longitude coordinates on the map as a parameter, and returns the corresponding pixel coordinates on the page.
Example of using toScreen() method

<template>
  <div id="viewDiv">
  </div>
</template>

<script setup>
import {
    
     onMounted } from 'vue'
import Map from '@arcgis/core/Map.js';
import MapView from '@arcgis/core/views/MapView.js'; 
import Point from "@arcgis/core/geometry/Point.js";

let view
onMounted(() => {
    
    
  initArcGisMap()
})

const initArcGisMap = () => {
    
    
  const map = new Map({
    
    
    basemap: "topo-vector"
  });

  view = new MapView({
    
    
    center: [-118.80500, 34.02700],
    zoom: 4,
    container: "viewDiv",
    map: map
  });
  view.ui.components = [];

  view.on('click', handleMapClick) 
}
  const handleMapClick = (event) => {
    
     
    const mapPoint = new Point({
    
    
        x: event.mapPoint.longitude,
        y: event.mapPoint.latitude,
        spatialReference: view.spatialReference
      });

      const screenPoint = view.toScreen(mapPoint);
      console.log(`点击点的屏幕坐标为 x:${
     
     screenPoint.x},y:${
     
     screenPoint.y}`)

  } 
</script>
<style scoped>  #viewDiv {
    
    
    width: 100%;
    height: 100vh;
  }
</style>

In the above code, when we click on the map, handleMapClickthe method will be called. In this method, we event.mapPointobtain the latitude and longitude coordinates on the map of the user's click location. Then, create an Pointobject to represent the coordinate point on the map and specify the corresponding spatial reference. Next, use view.toScreen(mapPoint)Convert map coordinate points to pixel coordinates on the page. Finally, the obtained pixel coordinates are printed on the console.
Run the program, click anywhere on the map, and you can see the screen coordinates of the point in the console
Insert image description here
. That’s it for the introduction of Map and MapView. For more information about ArcGIS Maps SDK for JavaScript, we will continue next time. chat.

おすすめ

転載: blog.csdn.net/w137160164/article/details/132261253