Adding attributes to a graphic

Graphics in a graphics layer have the ability to store attributes against each graphic which can be queried and displayed. Attributing graphics is normally performed when the Graphic instance is created. There is an overloaded constructor which allows for the attributes of a graphic to be specified alongside the symbol and geometry.

The following code shows how attributes are created in a Map<String,Object> prior to been assigned to a graphic:

//create some attributes for the graphic
Map<String,Object> attributes = new HashMap<String, Object>();
attributes.put("Name", "Complex Polygon Example");
attributes.put("Category", "Island");
attributes.put("hasLake", true);
 
//Graphic for complex polygon with attributes
Graphic complexPolyGraphic = new Graphic(complexPolygon, fillSymbol, attributes, 0);
 
//add the graphic to your graphics layer
myGraphicsLayer.addGraphic(complexPolyGraphic);

Now that your graphic has attributes associated with it, you may want to display these attributes to your application's users. The API has two built-in ways to display graphic or feature attributes to users: you can use the MapTip class to display attributes when the mouse hovers over a graphic, or you can use the InfoPopup class to display attributes in a popup window when a graphic is clicked. For more information on map tips, please see Adding map tips.

The code sample below shows how you would add map tips to the graphic we created above:

//create a maptip to display the graphic's attributes
MapTip maptip = new MapTip();
 
//specify the attributes displayed in the map tip
LinkedHashMap<String, String> displayfields = new LinkedHashMap<String, String>();
displayfields.put("Name", "Name: ");
displayfields.put("Category", "Category: ");
displayfields.put("hasLake", "has a lake: ");
maptip.setDisplayFields(displayfields);
 
//associate the maptip with the graphics layer
myGraphicsLayer.setMapTip(maptip);

When the user hovers the mouse over the graphic, a map tip will be displayed as in the screenshot below:

map tip displaying for a graphic

2/7/2013