Draw graphics

Download Sample Viewer

Description

This application shows how to use the toolkit's DrawingOverlay to interactively add graphics to the map. Once a graphic or feature is completed, a DrawingCompleteListener adds the graphic to our map's graphics layer.

Code snippet


    final DrawingOverlay drawingOverlay = new DrawingOverlay();
    map.addMapOverlay(drawingOverlay);
    drawingOverlay.setActive(true);
    drawingOverlay.addDrawingCompleteListener(new DrawingCompleteListener() {
        @Override
        public void drawingCompleted(DrawingCompleteEvent arg0) {
            graphicsLayer.addGraphic(drawingOverlay.getAndClearGraphic());
        }
    });
    drawingOverlay.setUp(DrawingMode.POLYLINE_FREEHAND, 
        new SimpleLineSymbol(Color.RED, 3), null);
  

Sample Code

/* Copyright 2014 Esri

All rights reserved under the copyright laws of the United States
and applicable international laws, treaties, and conventions.

You may freely redistribute and use this sample code, with or
without modification, provided you include the original copyright
notice and use restrictions.

See the use restrictions.*/
package com.esri.client.samples.graphics;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.image.BufferedImage;
import java.net.URL;

import javax.imageio.ImageIO;
import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLayeredPane;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.JToolBar;
import javax.swing.ToolTipManager;
import javax.swing.border.LineBorder;

import com.esri.core.geometry.Envelope;
import com.esri.core.map.Graphic;
import com.esri.core.symbol.PictureMarkerSymbol;
import com.esri.core.symbol.SimpleFillSymbol;
import com.esri.core.symbol.SimpleLineSymbol;
import com.esri.core.symbol.SimpleMarkerSymbol;
import com.esri.core.symbol.SimpleMarkerSymbol.Style;
import com.esri.core.symbol.Symbol;
import com.esri.map.ArcGISTiledMapServiceLayer;
import com.esri.map.GraphicsLayer;
import com.esri.map.JMap;
import com.esri.toolkit.overlays.DrawingCompleteEvent;
import com.esri.toolkit.overlays.DrawingCompleteListener;
import com.esri.toolkit.overlays.DrawingOverlay;
import com.esri.toolkit.overlays.DrawingOverlay.DrawingMode;

/***
 * This application shows how to use the toolkit's {@link DrawingOverlay}
 * to interactively add graphics to the map.  Once a graphic or
 * feature is completed, a {@link DrawingCompleteListener} adds the
 * graphic to our map's graphics layer.
 */
public class DrawGraphicsApp {

  // map
  private JMap map;
  // graphics layer
  private GraphicsLayer graphicsLayer;
  // base layer URL
  private static final String URL_BASEMAP =
      "http://services.arcgisonline.com/ArcGIS/rest/services/World_Topo_Map/MapServer";

  // ------------------------------------------------------------------------
  // Constructor
  // ------------------------------------------------------------------------
  public DrawGraphicsApp() {
  }

  // ------------------------------------------------------------------------
  // Core functionality
  // ------------------------------------------------------------------------
  /**
   * Creates and displays the UI, including the map, for this application.
   */
  public JComponent createUI() throws Exception {

    // application content
    JPanel applicationPanel = new JPanel();
    applicationPanel.setLayout(new BorderLayout(0, 0));

    // create map
    map = new JMap();
    // set map extent to downtown London
    map.setExtent(new Envelope(-18926.234, 6708788.348, -10680.428, 6714288.35));

    // add tiled layer
    ArcGISTiledMapServiceLayer tiledLayer = new ArcGISTiledMapServiceLayer(URL_BASEMAP);
    map.getLayers().add(tiledLayer);

    // add graphics layer for our drawn graphics
    graphicsLayer = new GraphicsLayer();
    map.getLayers().add(graphicsLayer);

    // create drawing overlay, add to map, and activate
    final DrawingOverlay drawingOverlay = new DrawingOverlay();
    map.addMapOverlay(drawingOverlay);
    drawingOverlay.setActive(true);

    // add a listener to add the drawn graphic into our graphics layer
    drawingOverlay.addDrawingCompleteListener(new DrawingCompleteListener() {

      @Override
      public void drawingCompleted(DrawingCompleteEvent arg0) {
        // gets the graphic and clears it from the overlay
        graphicsLayer.addGraphic((Graphic) drawingOverlay.getAndClearFeature());
      }
    });

    // button toolbar
    final JToolBar toolBar = createToolBar(drawingOverlay);

    // map and description panel
    JLayeredPane contentPane = createContentPane();
    JPanel description = createDescription();
    description.setLocation(10, 10);
    contentPane.add(description);
    contentPane.add(map);

    applicationPanel.add(toolBar, BorderLayout.NORTH);
    applicationPanel.add(contentPane, BorderLayout.CENTER);

    return applicationPanel;
  }

  /**
   * Create a toolbar with our drawing tool buttons. Clicking a button will
   * change the drawing mode and symbology (and attributes, optionally) to
   * that specified in the setUp method.
   * @param drawingOverlay - the drawing overlay associated with the toolbar
   * @return toolBar - the toolBar
   */
  private JToolBar createToolBar(final DrawingOverlay drawingOverlay) {

    JToolBar toolBar = new JToolBar();
    toolBar.setLayout(new FlowLayout(FlowLayout.CENTER));

    ToolTipManager.sharedInstance().setInitialDelay(100);

    // rectangle
    JButton rectangleButton = new JButton(new ImageIcon(getClass().getResource(
        "/com/esri/client/toolkit/images/EditingRectangleTool16.png")));
    rectangleButton.setToolTipText("Rectangle tool");
    rectangleButton.addActionListener(new ActionListener() {
      @Override
      public void actionPerformed(ActionEvent e) {
        drawingOverlay.setUp(
            DrawingMode.POLYGON_RECTANGLE,
            new SimpleFillSymbol(new Color(200, 0, 0, 60), new SimpleLineSymbol(new Color(200, 0, 0), 3)),
            null);
      }
    });
    toolBar.add(rectangleButton);

    // polyline
    JButton polylineButton = new JButton(new ImageIcon(getClass().getResource(
        "/com/esri/client/toolkit/images/EditingLineTool16.png")));
    polylineButton.setToolTipText("Polyline tool");
    polylineButton.addActionListener(new ActionListener() {
      @Override
      public void actionPerformed(ActionEvent e) {
        drawingOverlay.setUp(
            DrawingMode.POLYLINE,
            new SimpleLineSymbol(new Color(0, 0, 150), 3),
            null);
      }
    });
    toolBar.add(polylineButton);

    // freehand line - another option not shown is freehand polygon
    JButton freehandLineButton = new JButton(new ImageIcon(getClass().getResource(
        "/com/esri/client/toolkit/images/EditingFreehandTool16.png")));
    freehandLineButton.setToolTipText("Freehand line tool");
    freehandLineButton.addActionListener(new ActionListener() {
      @Override
      public void actionPerformed(ActionEvent e) {
        drawingOverlay.setUp(
            DrawingMode.POLYLINE_FREEHAND,
            new SimpleLineSymbol(new Color(200, 0, 0), 3),
            null);
      }
    });
    toolBar.add(freehandLineButton);

    // point
    JButton pointButton = new JButton(new ImageIcon(getClass().getResource(
        "/com/esri/client/toolkit/images/EditingPointTool16.png")));
    pointButton.setToolTipText("Point tool");
    pointButton.addActionListener(new ActionListener() {
      @Override
      public void actionPerformed(ActionEvent e) {
        drawingOverlay.setUp(
            DrawingMode.POINT,
            createSimpleMarkerSymbol(),
            null);
      }
    });
    toolBar.add(pointButton);

    // polygon
    final SimpleLineSymbol dottedLine = new SimpleLineSymbol(Color.BLACK, 2);
    dottedLine.setStyle(SimpleLineSymbol.Style.DASH);
    JButton polygonButton = new JButton(new ImageIcon(getClass().getResource(
        "/com/esri/client/toolkit/images/EditingPolygonTool16.png")));
    polygonButton.setToolTipText("Polygon tool");
    polygonButton.addActionListener(new ActionListener() {
      @Override
      public void actionPerformed(ActionEvent e) {
        drawingOverlay.setUp(
            DrawingMode.POLYGON,
            new SimpleFillSymbol(new Color(0, 0, 0, 80), dottedLine),
            null);
      }
    });
    toolBar.add(polygonButton);

    return toolBar;
  }

  // ------------------------------------------------------------------------
  // Static methods
  // ------------------------------------------------------------------------
  /**
   * Launch the application.
   */
  public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable() {
      @Override
      public void run() {
        try {
          DrawGraphicsApp app = new DrawGraphicsApp();
          JFrame appWindow = app.createWindow();
          appWindow.add(app.createUI());
          appWindow.setVisible(true);
        } catch (Exception e) {
          e.printStackTrace();
        }
      }
    });
  }

  // ------------------------------------------------------------------------
  // Private methods
  // ------------------------------------------------------------------------
  private Symbol createSimpleMarkerSymbol() {

    PictureMarkerSymbol symbol = null;
    BufferedImage image = null;

    URL url = this.getClass().getResource("resources/RedStickpin.png");
    try {
      image = ImageIO.read(url);
      symbol = new PictureMarkerSymbol(image);
      symbol.setSize(36, 36);
      symbol.setOffsetY(16.0f);
    }
    catch (Exception e) {
      System.err.println("unable to create picture marker symbol");
      e.printStackTrace();
      return new SimpleMarkerSymbol(Color.RED, 15, Style.DIAMOND);
    }
    return symbol;
  }

  /**
   * Creates a window.
   * @return a window.
   */
  private JFrame createWindow() {
    JFrame window = new JFrame("Draw Graphics Application");
    window.setBounds(100, 100, 1000, 700);
    window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    window.getContentPane().setLayout(new BorderLayout(0, 0));
    window.addWindowListener(new WindowAdapter() {
      @Override
      public void windowClosing(WindowEvent windowEvent) {
        super.windowClosing(windowEvent);
        map.dispose();
      }
    });
    return window;
  }

  /**
   * Creates a content pane.
   * @return a content pane.
   */
  private static JLayeredPane createContentPane() {
    JLayeredPane contentPane = new JLayeredPane();
    contentPane.setLayout(new BorderLayout(0, 0));
    contentPane.setVisible(true);
    return contentPane;
  }

  /**
   * Creates a description for this application.
   * @return description
   */
  private JPanel createDescription() {
    JPanel descriptionContainer = new JPanel();
    descriptionContainer.setLayout(new BoxLayout(descriptionContainer, 0));
    descriptionContainer.setSize(280, 100);
    JTextArea description = new JTextArea(
        "Select a drawing tool button above to interactively add graphics " +
            "to the map using the mouse. To draw multipath geometries, right " +
        "click and select 'Create new path' once you have finished drawing a path.");
    description.setFont(new Font("Verdana", Font.PLAIN, 11));
    description.setForeground(Color.WHITE);
    description.setBackground(new Color(0, 0, 0, 180));
    description.setEditable(false);
    description.setLineWrap(true);
    description.setWrapStyleWord(true);
    description.setBorder(BorderFactory.createEmptyBorder(5,10,5,5));
    descriptionContainer.add(description);
    descriptionContainer.setBackground(new Color(0, 0, 0, 0));
    descriptionContainer.setBorder(new LineBorder(Color.BLACK, 3, false));
    return descriptionContainer;
  }
}
Feedback on this topic?