Map options

Download Sample Viewer

Description

This application shows how to create a JMap using a MapOptions instance, giving you the option to easily set a map type (base layer), latitude and longitude around which to center the map, and zoom level for the map. The MapOptions class is then used to switch the type of basemap in the map on-the-fly. In addition, simple marker graphics (point) can be added directly to the JMap using the addMarkerGraphic methods. Popups are enabled by default on these marker graphics. To disable these popups, use setMarkerGraphicPopupsEnabled(boolean), passing in false to disable. For quickly finding an address or location, static methods on the Locator class exists which either take or return input as lat-lon coordinates. In this application, the Locator.findAddress static method is used to locate (geocode) the search string entered in the application's text field. The top result is shown on the map using a marker graphic.

Code snippet


  // map options: topographic map, centered at lat-lon 57.5N 5W (Scotland), zoom level 7
  MapOptions mapOptions = new MapOptions(MapType.TOPO, 57.5000, -5.0000, 6);

  // create the map using MapOptions
  map = new JMap(mapOptions);

  // add marker graphic directly to the map
  map.addMarkerGraphic(58.0440, -5.2088, // lat, lon
  "Stac Pollaidh", // title
  "Iconic mountain in the North-West Highlands in Scotland.", // description
  "http://www.neotryte.com/images/stac_pollaidh_th.jpg", // image URL
  "http://en.wikipedia.org/wiki/Stac_Pollaidh", // link URL when image clicked
  null //default marker        
  );
  

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

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.net.URL;
import java.util.List;

import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.JToolBar;
import javax.swing.SwingUtilities;
import javax.swing.ToolTipManager;

import com.esri.core.map.CallbackListener;
import com.esri.core.tasks.geocode.Locator;
import com.esri.core.tasks.geocode.LocatorGeocodeResult;
import com.esri.map.JMap;
import com.esri.map.MapOptions;
import com.esri.map.MapOptions.MapType;

/**
 * This application shows how to create a ({@link JMap}) using a {@link MapOptions} instance, 
 * giving you the option to easily set a map type (base layer), latitude and longitude around 
 * which to center the map, and zoom level for the map. The MapOptions class is then used to 
 * switch the type of basemap in the map on-the-fly.
 * <p>
 * In addition, simple marker graphics (point) can be added directly to the JMap using 
 * {@link JMap#addMarkerGraphic(double, double, String, String)} and 
 * {@link JMap#addMarkerGraphic(double, double, String, String, String, String, java.awt.image.BufferedImage)}.
 * Popups are enabled by default on these marker graphics. To disable these popups, use 
 * {@link JMap#setMarkerGraphicPopupsEnabled(boolean)}, passing in false to disable.
 * <p>
 * For quickly finding an address or location, static methods on the {@link Locator} 
 * class exists which either take or return input as lat-lon coordinates. In this application, 
 * the {@link Locator#findAddress(double, double, Locator, CallbackListener)} method is 
 * used to locate (geocode) the search string entered in the application's text field. 
 * The top result is shown on the map using a marker graphic.
 */
public class MapOptionsApp {

  private JMap map;
  private JPanel contentPane;

  // default constructor
  public MapOptionsApp() { }

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

    // application content
    contentPane = new JPanel(new BorderLayout());

    // map options: topographic map, centered at lat-lon 57.5N 5W (Scotland), zoom level 7
    MapOptions mapOptions = new MapOptions(MapType.TOPO, 57.5000, -5.0000, 6);

    // create the map using MapOptions
    map = new JMap(mapOptions);
    contentPane.add(map, BorderLayout.CENTER);

    // add marker graphic directly to the map
    map.addMarkerGraphic(58.0440, -5.2088, // lat, lon
        "Stac Pollaidh", // title
        "Iconic mountain in the North-West Highlands in Scotland.", // description
        "http://www.neotryte.com/images/stac_pollaidh_th.jpg", // image URL
        "http://en.wikipedia.org/wiki/Stac_Pollaidh", // link URL when image clicked
        null //default marker
        );

    JToolBar basemapBar = new JToolBar();
    FlowLayout layout = new FlowLayout(FlowLayout.CENTER);
    layout.setHgap(0);
    layout.setVgap(0);
    basemapBar.setLayout(layout);
    ToolTipManager.sharedInstance().setInitialDelay(10);
    contentPane.add(basemapBar, BorderLayout.NORTH);

    // listener to switch map types when button clicked
    final ActionListener listener = new ActionListener() {
      @Override
      public void actionPerformed(ActionEvent e) {
        // switch basemap via map options
        String typeString = ((JButton)e.getSource()).getActionCommand();
        MapType type = MapType.valueOf(typeString);
        map.setMapOptions(new MapOptions(type));
      }
    };

    for (MapType type : MapOptions.MapType.values()) {
      String basemapString = type.toString();
      JButton button = new JButton(loadImageIcon("resources/"+ basemapString + ".png"));
      button.setActionCommand(basemapString);
      button.setToolTipText(basemapString);
      button.addActionListener(listener);
      basemapBar.add(button);
    }

    JCheckBox cb = new JCheckBox("Enable popups");
    cb.setSelected(true);
    cb.addItemListener(new ItemListener() {

      @Override
      public void itemStateChanged(ItemEvent e) {
        if (e.getStateChange() == ItemEvent.SELECTED) {
          map.setMarkerGraphicPopupsEnabled(true);
        } else {
          map.setMarkerGraphicPopupsEnabled(false);
        }
      }
    });

    // search box
    final JTextField searchBox = new JTextField("Edinburgh");
    searchBox.setPreferredSize(new Dimension(200, 30));

    ActionListener onFindAndEnter = new ActionListener() {

      @Override
      public void actionPerformed(ActionEvent e) {
        final String searchText = searchBox.getText();
        if (searchText != null && !searchText.trim().isEmpty()) {
          Locator.findLocation(searchText, null, new CallbackListener<List<LocatorGeocodeResult>>() {

            @Override
            public void onError(Throwable error) {
              JOptionPane.showMessageDialog(contentPane, "An error has occured. Please try again.", "", JOptionPane.ERROR_MESSAGE);
              error.printStackTrace();
            }

            @Override
            public void onCallback(List<LocatorGeocodeResult> results) {
              // check if we have any results 
              if (results == null || results.size() == 0) {
                JOptionPane.showMessageDialog(contentPane, "No address found.", "", JOptionPane.ERROR_MESSAGE);
              } else {
                // add a marker at the found location, on the UI thread
                final LocatorGeocodeResult topResult = results.get(0);
                SwingUtilities.invokeLater(new Runnable() {

                  @Override
                  public void run() {
                    double lat = topResult.getLocation().getY(); // latitude
                    double lon = topResult.getLocation().getX(); // longitude
                    map.addMarkerGraphic(lat, lon, searchText, topResult.getAddress());
                    map.centerAt(lat, lon);
                  }
                });
              }
            }
          });
        }
      }
    };

    JButton findButton = new JButton("Find");
    findButton.addActionListener(onFindAndEnter);
    searchBox.addActionListener(onFindAndEnter);

    JButton clearButton = new JButton("Clear marker graphics");
    clearButton.addActionListener(new ActionListener() {

      @Override
      public void actionPerformed(ActionEvent e) {
        map.removeAllMarkerGraphics();
      }
    });

    JToolBar controls = new JToolBar();
    controls.setLayout(new FlowLayout());
    controls.add(cb);
    controls.add(searchBox);
    controls.add(findButton);
    controls.add(clearButton);

    contentPane.add(controls, BorderLayout.SOUTH);

    return contentPane;
  }

  /**
   * Starting point of this application.
   * @param args arguments to this application.
   */
  public static void main(String[] args) {
    SwingUtilities.invokeLater(new Runnable() {
      @Override
      public void run() {
        try {
          // instance of this application
          MapOptionsApp mapExtentApp = new MapOptionsApp();
          // create the UI, including the map, for the application.
          JFrame appWindow = mapExtentApp.createWindow();
          appWindow.add(mapExtentApp.createUI());
          appWindow.setVisible(true);
        } catch (Exception e) {
          // on any error, display the stack trace.
          e.printStackTrace();
        }
      }
    });
  }

  private JFrame createWindow() {
    JFrame window = new JFrame("Map Options Application");
    window.setSize(1000, 700);
    window.setLocationRelativeTo(null);
    window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    window.getContentPane().setLayout(new BorderLayout());
    window.addWindowListener(new WindowAdapter() {
      @Override
      public void windowClosing(WindowEvent windowEvent) {
        super.windowClosing(windowEvent);
        map.dispose();
      }
    });
    return window;
  }

  protected static ImageIcon loadImageIcon(String imageFilePath) {
    Image image = null;
    try {
      URL url = MapOptionsApp.class.getResource(imageFilePath);
      image = ImageIO.read(url);
    } catch (Exception e1) {
      e1.printStackTrace();
    }
    if (image != null) {
      return new ImageIcon(image);
    }
    return null;
  }
}
Feedback on this topic?