Map grid

Download Sample Viewer

Description

This application shows how to add a Grid to a map. Various grid types (GridType) can be chosen from, including MGRS (Military Grid Reference System) and LAT_LON (latitude and longitude). The grid visibility can be turned on or off via a check box, and various properties can be set on the grid labels, including whether to position them geographically or fixed to certain parts of the screen (setLabelPosition), and if fixed on screen, the pixel offset from the edges of the screen (setLabelOffset). When you change the grid type, any custom grid colors and label properties are reset to the defaults for that grid type. No 'getters' are available for grid properties, so you will have to re-apply any properties to see the effects, for example by re-selecting an option in the drop-down menus.

Note: labels may only be visible at a large scale, and label settings do not apply to UTM grids which don't have grid levels appropriate for labeling position changes.

Code snippet


    // adds an MGRS Grid to map
    map.getGrid().setType(GridType.MGRS);

    // hides the grid
    map.getGrid().setVisibility(false);
  
  // hides the grid labels
    map.getGrid().setLabelVisibility(false);
  

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.displayinfo;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.JToolBar;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;

import com.esri.map.MapOptions;
import com.esri.map.Grid.GridType;
import com.esri.map.Grid;
import com.esri.map.Grid.LabelPosition;
import com.esri.map.MapOptions.MapType;
import com.esri.map.JMap;
import javax.swing.JComboBox;
import javax.swing.border.TitledBorder;

import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

/**
 * This application shows how to add a Grid to a map. Various grid types ({@link GridType}) 
 * can be chosen from, including MGRS (Military Grid Reference System) and LAT_LON 
 * (latitude and longitude). The grid visibility can be turned on or off via a check box, 
 * and various properties can be set on the grid labels, including whether to position 
 * them geographically or fixed to certain parts of the screen (<code>setLabelPosition</code>), 
 * and if fixed on screen, the pixel offset from the edges of the screen (<code>setLabelOffset</code>).
 * <p>
 * When you change the grid type, any custom grid colors and label properties are reset 
 * to the defaults for that grid type. No 'getters' are available for grid properties, so 
 * you will have to re-apply any properties to see the effects, for example by re-selecting
 * an option in the drop-down menus.
 * <p>
 * Note that labels may only be visible at a large scale, and label settings do not apply to 
 * UTM grids which don't have grid levels appropriate for labeling position changes.
 */
public class GridApp {

  private JComponent contentPane;
  private JMap map;
  private JTextField offsetField;
  private MyCheckBox chkCustomStyle;
  private MyComboBox cbTypes;
  private MyComboBox cbLabelPosition;
  private MyComboBox cbMGRSLabelUnits;
  private MyComboBox cbLatLonLabelUnits;
  private static final Dimension BUTTON_DIM = new Dimension(180, 30);

  // ------------------------------------------------------------------------
  // Default constructor
  // ------------------------------------------------------------------------
  public GridApp() { }

  // ------------------------------------------------------------------------
  // Core functionality
  // ------------------------------------------------------------------------
  /**
   * Changes the type of grid to display over the map, for example MGRS, USNG, or LAT_LON.
   */
  private void updateGridType() {
    map.getGrid().setType((Grid.GridType)cbTypes.getSelectedItem());
  }
  
  /**
   * Shows or hides the grid based on whether a UI component was selected or 
   * deselected.
   * 
   * @param e the item event from the UI component
   */
  private void updateGridVisiblity(ItemEvent e) {
    if (e.getStateChange() == ItemEvent.DESELECTED) {
      // hide the grid
      map.getGrid().setVisibility(false);
    } else if (e.getStateChange() == ItemEvent.SELECTED) {
      // show the grid
      map.getGrid().setVisibility(true);
    }
  }
  
  /**
   * Shows or hides the grid labels based on whether a UI component was selected or 
   * deselected.
   * 
   * @param e the item event from the UI component
   */
  private void updateLabelVisibility(ItemEvent e) {
    if (e.getStateChange() == ItemEvent.DESELECTED) {
      // hide the grid labels
      map.getGrid().setLabelVisibility(false);
    } else if (e.getStateChange() == ItemEvent.SELECTED) {
      // show the grid labels
      map.getGrid().setLabelVisibility(true);
    }
  }

  /**
   * Sets custom grid colors (line/label) and line widths for each grid level of the grid.
   */
  private void setupCustomColors() {
    int gridLevels = map.getGrid().getLevelCount();
    for (int level = 0; level < gridLevels; level++) {
      map.getGrid().setLineColor(level, Color.BLUE);
      map.getGrid().setLabelColor(level, Color.CYAN);
      map.getGrid().setLineWidth(level, 1);
    }
  }
  
  /**
   * Sets the label positioning based on what is selected in the combo box UI component.
   */
  private void updateLabelPosition() {
    Grid.LabelPosition position = (LabelPosition) cbLabelPosition.getSelectedItem();
    map.getGrid().setLabelPosition(position);
  }
  
  /**
   * Sets the label offset based on what is entered in the offset text field; not 
   * applicable for GEOGRAPHIC label position type. 
   */
  private void updateLabelOffset() {
    try {
      int newOffset = Integer.parseInt(offsetField.getText());
      map.getGrid().setLabelOffset(newOffset);
    } catch (Exception ex) {
      System.err.println("Error parsing or applying label offset");
      ex.printStackTrace();
    }
  }
  
  /**
   * Sets the LAT_LON label units, based on what is selected in the combo box UI component.
   * Has no effect unless LAT_LON grid type is selected.
   */
  private void updateLatLonLabelUnits() {
    Grid.LatLonLabelUnit unit = (Grid.LatLonLabelUnit) cbLatLonLabelUnits.getSelectedItem();
    map.getGrid().setLatLonLabelUnits(unit);
  }
  
  /**
   * Sets the MGRS (or USNG) label units for scales showing metres/km, based on 
   * what is selected in the combo box UI component. Has no effect unles MGRS or USNG 
   * grid type is selected.
   */
  private void updateMGRSLabelUnits() {
    Grid.MGRSLabelUnit unit = (Grid.MGRSLabelUnit) cbMGRSLabelUnits.getSelectedItem();
    map.getGrid().setMGRSLabelUnits(unit);
  }

  // ------------------------------------------------------------------------
  // Public methods
  // ------------------------------------------------------------------------
  /**
   * Creates the UI for this application, including the map and info panel
   * @return the content pane with the application content
   */
  public JComponent createUI() {

    contentPane = new JPanel();
    contentPane.setLayout(new BorderLayout(0, 0));

    map = createMap();
    JToolBar tb = createToolbar();

    contentPane.add(tb, BorderLayout.WEST);
    contentPane.add(map, BorderLayout.CENTER);

    return contentPane;
  }

  // ------------------------------------------------------------------------
  // Static methods
  // ------------------------------------------------------------------------
  public static void main(String[] args) {
    SwingUtilities.invokeLater(new Runnable() {
      @Override
      public void run() {
        try {
          // instance of this application
          GridApp gridApp = new GridApp();

          // create the UI, including the map, for the application.
          JFrame appWindow = gridApp.createWindow();
          appWindow.getContentPane().add(gridApp.createUI());
          appWindow.setVisible(true);
        } catch (Exception e) {
          // on any error, display the stack trace.
          e.printStackTrace();
        }
      }
    });
  }

  // ------------------------------------------------------------------------
  // Private methods
  // ------------------------------------------------------------------------
  /**
   * Creates a map using map options to set the basemap, center point, and zoom level.
   * @return a map.
   */
  private JMap createMap() {
    MapOptions mapOptions = new MapOptions(MapType.SATELLITE, 34.0515888762, -117.190346717, 12);
    JMap jMap = new JMap(mapOptions);
    
    return jMap;
  }

  /**
   * Creates the panel to display grid options to the user.
   */
  private JToolBar createToolbar() {

    JToolBar toolbar = new JToolBar(SwingConstants.VERTICAL);
    toolbar.setBackground(Color.BLACK);

    JPanel panelGrid = new JPanel();
    panelGrid.setLayout(new BoxLayout(panelGrid, BoxLayout.Y_AXIS));
    panelGrid.setAlignmentX(SwingConstants.LEFT);
    TitledBorder b1 = BorderFactory.createTitledBorder("Grid: ");
    b1.setTitleColor(Color.WHITE);
    panelGrid.setBorder(b1);
    panelGrid.setBackground(Color.BLACK);

    JLabel txtGridType = new MyLabel("Grid Type: ");
    //combo box containing grid types
    cbTypes = new MyComboBox(Grid.GridType.values());
    cbTypes.addActionListener(new ActionListener() {
      @Override
      public void actionPerformed(ActionEvent arg0) {
        updateGridType();
        // make sure custom style box unticked
        if (chkCustomStyle != null) {
          chkCustomStyle.setSelected(false);
        }
      }
    });
    cbTypes.setSelectedIndex(1); // MGRS to start

    JCheckBox chkGridVisible = new MyCheckBox("Grid Visible", true);
    chkGridVisible.addItemListener(new ItemListener() {

      @Override
      public void itemStateChanged(ItemEvent e) {
        updateGridVisiblity(e);
      }
    });

    JCheckBox chkLabelsVisible = new MyCheckBox("Labels Visible", true);
    chkLabelsVisible.addItemListener(new ItemListener() {
      @Override
      public void itemStateChanged(ItemEvent e) {
        updateLabelVisibility(e);
      }
    });

    chkCustomStyle = new MyCheckBox("Custom Colors", false);
    chkCustomStyle.addItemListener(new ItemListener() {
      @Override
      public void itemStateChanged(ItemEvent event) {
        if (event.getStateChange() == ItemEvent.DESELECTED) {
          // return grid to default settings.  Achieved by regenerating the grid.
          map.getGrid().setType(GridType.None);
          updateGridType();
        } else if (event.getStateChange() == ItemEvent.SELECTED) {
          // set up some custom grid colors and line widths
          setupCustomColors();
        }
      }
    });

    panelGrid.add(txtGridType);
    panelGrid.add(cbTypes);
    panelGrid.add(chkGridVisible);
    panelGrid.add(chkLabelsVisible);
    panelGrid.add(chkCustomStyle);

    JPanel panelGridLabels = new JPanel();
    panelGridLabels.setLayout(new BoxLayout(panelGridLabels, BoxLayout.Y_AXIS));
    panelGridLabels.setAlignmentX(SwingConstants.LEFT);
    TitledBorder b2 = BorderFactory.createTitledBorder("Grid Labels: ");
    b2.setTitleColor(Color.WHITE);
    panelGridLabels.setBorder(b2);
    panelGridLabels.setBackground(Color.BLACK);

    cbLabelPosition = new MyComboBox(Grid.LabelPosition.values());
    cbLabelPosition.addActionListener(new ActionListener() {

      @Override
      public void actionPerformed(ActionEvent e) {
        updateLabelPosition();
      }
    });

    JLabel l2 = new MyLabel("Label positioning:");
    panelGridLabels.add(l2);
    panelGridLabels.add(cbLabelPosition);

    cbLatLonLabelUnits = new MyComboBox(Grid.LatLonLabelUnit.values());
    cbLatLonLabelUnits.addActionListener(new ActionListener() {

      @Override
      public void actionPerformed(ActionEvent e) {
        updateLatLonLabelUnits();
      }
    });

    JLabel l1 = new MyLabel("Label offset (pixels):");
    offsetField = new JTextField(5);
    offsetField.setText("45");
    offsetField.setEditable(true);
    JButton apply1 = new JButton("Apply offset");
    apply1.addActionListener(new ActionListener() {

      @Override
      public void actionPerformed(ActionEvent e) {
        updateLabelOffset();
      }
    });

    JPanel p1 = new JPanel();
    p1.setPreferredSize(BUTTON_DIM);
    p1.setMaximumSize(BUTTON_DIM);
    p1.setAlignmentX(SwingConstants.LEFT);
    p1.setBackground(Color.BLACK);
    p1.setLayout(new BorderLayout());
    p1.add(offsetField, BorderLayout.WEST);
    p1.add(apply1, BorderLayout.CENTER);

    panelGridLabels.add(l1);
    panelGridLabels.add(p1);

    JLabel l3 = new MyLabel("LAT_LON label units:");
    panelGridLabels.add(l3);
    panelGridLabels.add(cbLatLonLabelUnits);

    cbMGRSLabelUnits = new MyComboBox(Grid.MGRSLabelUnit.values());
    cbMGRSLabelUnits.addActionListener(new ActionListener() {

      @Override
      public void actionPerformed(ActionEvent e) {
        updateMGRSLabelUnits();
      }
    });
    cbMGRSLabelUnits.setSelectedIndex(1);
    JLabel l4 = new MyLabel("MGRS/USNG label units:");
    panelGridLabels.add(l4);
    panelGridLabels.add(cbMGRSLabelUnits);

    toolbar.add(panelGrid);
    toolbar.add(panelGridLabels);

    return toolbar;
  }

  /**
   * Creates a window.
   * @return a window.
   */
  private JFrame createWindow() {
    JFrame window = new JFrame("Grid 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;
  }

  // UI classes for simplicity
  class MyLabel extends JLabel {
    private static final long serialVersionUID = 1L;

    public MyLabel(String string) {
      super(string);
      setPreferredSize(BUTTON_DIM);
      setMaximumSize(BUTTON_DIM);
      setAlignmentX(SwingConstants.LEFT);
      setForeground(Color.WHITE);
      setBackground(Color.BLACK);
    }
  }

  class MyComboBox extends JComboBox<Object> {
    private static final long serialVersionUID = 1L;

    public MyComboBox(Object[] values) {
      super(values);
      setPreferredSize(BUTTON_DIM);
      setMaximumSize(BUTTON_DIM);
      setAlignmentX(SwingConstants.LEFT);
    }
  }

  class MyCheckBox extends JCheckBox {
    private static final long serialVersionUID = 1L;

    public MyCheckBox(String text, boolean selected) {
      super(text, selected);
      setBackground(Color.BLACK);
      setForeground(Color.WHITE);
      setPreferredSize(BUTTON_DIM);
      setMaximumSize(BUTTON_DIM);
      setAlignmentX(SwingConstants.LEFT);
    }
  }
}
Feedback on this topic?