ArcGIS API for JavaScript 4.6 2DmapView map annotation
When using ArcGIS for annotation a while ago, we found that according to the LabelClass provided in the sdk, map annotation could not be realized. After careful inspection, we found that
LabelClass does not support mapView of 2d map. However, it has to find a way.
1. Create a GraphicsLayer to store the acquired data and display it on the map.
2. Monitor the layers to be labeled and use updating to query and obtain data.
3. Create a graph from the acquired data according to the corresponding geometry.type, and bind the annotation information with the graph,
According to its (x/y) coordinate / latitude (latitude/longitude) value, the position of the figure is obtained.
4.add into GraphicLayer.
1. Implementation code
//featureLayer = the layer you want to label var pointLabelLayer = new GraphicsLayer({ title: "Annotation layer" }) var polygonLabelLayer = new GraphicsLayer({ title: "Annotation layer" }) //-------------------------Point dimension---------------------------- map.add(pointLabelLayer) map.add(polygonLabelLayer) view.when(function() { view.whenLayerView(featureLayer).then(function(sthView) { //console.log(sthView) sthView.watch("updating",function() { pointLabelLayer.removeAll(); sthView.queryFeatures().then(function(results) { //console.log(results) results.forEach(function(oneLabel) { //console.log("oneLabel",oneLabel) pointLabelLayer.add(new Graphic({ geometry: { type: oneLabel.geometry.type, x: oneLabel.geometry.x, y: oneLabel.geometry.y, spatialReference: oneLabel.geometry.spatialReference }, symbol: { type: "text", color: "blue", haloSize: 2, haloColor: "white", xoffset: 15, yoffset: -15, text: pointLabel.attributes["name"],//Here is the field displayed in the annotation font: { size: 10, family: "sans-serif", weight: "bolder" } } })) }) }) }) }) //-------------------------Face annotation---------------------------- view.whenLayerView(featureLayer).then(function(sthView) { sthView.watch("updating",function() { polygonLabelLayer.removeAll(); sthView.queryFeatures().then(function(results) { results.forEach(function(oneLabel) { var cenPo = new Point({ latitude: oneLabel.geometry.centroid.latitude, //longitude/latitude is not worth it, that is, x/y should longitude: oneLabel.geometry.centroid.longitude, spatialReference: oneLabel.geometry.centroid.spatialReference }) polygonLabelLayer.add(new Graphic({ geometry: cenPo, symbol: { type: "text", color: "purple", haloSize: 2, haloColor: "white", text: oneLabel.attributes["name"], font: { size: 10, family: "sans-serif", weight: "bolder" } } })) }) }) }) }) })
Appendix. How to make the annotation layer and featureLayer show and hide at the same time
//Just add it to view.when() view.whenLayerView(pointLabelLayer).then(function(vis) { vis.watch("visible", function() { if(pointLabelLayer.visible == true) { pointLabelLayer.visible = true }else { pointLabelLayer.removeAll(); pointLabelLayer.visible = false } }) })