杰瑞科技汇

java arcengine

Of course! Here is a comprehensive guide to using Java with ArcGIS Engine, covering what it is, why you'd use it, core concepts, a step-by-step tutorial, and best practices.


What is ArcGIS Engine?

ArcGIS Engine is a developer toolkit that provides a set of components for embedding GIS functionality into your own applications. It's not a standalone application like ArcGIS Pro or ArcMap; instead, it's a library of classes, controls, and tools that you use to build custom GIS applications.

Key Characteristics:

  • Platform: It's available for multiple platforms, including Windows (C++, .NET, Java) and Linux (C++).
  • Functionality: It allows you to work with maps, perform spatial analysis, manage geographic data, and create custom UIs.
  • Licensing: Applications built with Engine require an ArcGIS Engine Runtime license to be installed on the end-user's machine.
  • Java Support: Esri officially supports Java for building ArcGIS Engine applications, making it a great choice for enterprise-level applications or integrating with existing Java-based systems.

Why Use Java with ArcGIS Engine?

  • Enterprise Integration: Seamlessly integrate GIS capabilities into large, existing Java-based enterprise systems (e.g., financial, logistics, or natural resource management platforms).
  • Cross-Platform Potential: While the primary focus is Windows, Java's "write once, run anywhere" philosophy can be beneficial for certain deployment scenarios.
  • Robust Ecosystem: Leverage the vast Java ecosystem for things like database connectivity (JDBC), web services, testing frameworks (JUnit), and application servers (Tomcat, JBoss).
  • Strong Community: A large developer community means plenty of resources, forums, and potential for hiring.

Core Concepts in ArcGIS Engine (Java)

To work with Engine, you need to understand a few fundamental classes and interfaces. Think of them as the building blocks of your application.

Class/Interface Purpose Analogy
AoInitialize Manages the licensing of the ArcGIS Engine. The license key that unlocks the software.
MapDocument Represents a map document (.mxd or .pmf). It holds the map, layers, and data frame properties. The blueprint of your map.
Map The actual map object, containing layers and controlling its properties (like extent). The canvas where your data is drawn.
MapControl The visual UI component (like a JPanel) that displays the Map object. It handles user interaction (pan, zoom, etc.). The picture frame that holds the canvas.
Layer An abstract class for any data layer (e.g., FeatureLayer, RasterLayer, GroupLayer). A single sheet of paper with data on it (e.g., roads, parcels).
FeatureLayer A specific type of layer that represents vector data (e.g., shapefiles, geodatabase feature classes). A vector data sheet.
FeatureClass The underlying dataset (e.g., a shapefile) that a FeatureLayer is based on. The actual data file on your hard drive.
Geometry Represents the shape of a geographic feature (e.g., Point, Polyline, Polygon). The actual shape (a dot, a line, an area) on your data sheet.

Step-by-Step: Creating a Simple Java ArcGIS Engine Application

This guide will walk you through creating a basic Java Swing application that loads a map document and displays it in a map control.

Prerequisites

  1. ArcGIS Engine Runtime: You must have the ArcGIS Engine Runtime for Java installed on your development machine. You can download it from the Esri Customer Care portal.
  2. An IDE: IntelliJ IDEA or Eclipse.
  3. Java Development Kit (JDK): A compatible version (check Esri's documentation for specifics).
  4. Map Document: Create a simple .mxd file in ArcMap or ArcGIS Pro with a few layers (e.g., a cities shapefile and a states shapefile). Save it as C:\Data\MyMap.mxd.

Step 1: Set Up Your Project in Eclipse

  1. Create a new Java Project in Eclipse.
  2. Right-click on the project -> Build Path -> Configure Build Path.
  3. Go to the Libraries tab and click Add External JARs....
  4. Navigate to your ArcGIS Engine installation directory. The default path is C:\Program Files (x86)\ArcGIS\EngineJava10.x\bin (the version number x will vary).
  5. Select and add the following JAR files:
    • esri.jar
    • js.jar (for Swing components)
    • jhall.jar (for Java help)
    • Also, add the jna.jar file, which is usually located in a lib subfolder within the EngineJava directory.
  6. Click Apply and Close.

Step 2: Write the Java Code

Create a new Java class named EngineViewer and paste the following code into it. The code is heavily commented to explain each step.

import com.esri.arcgis.controls.*;
import com.esri.arcgis.display.*;
import com.esri.arcgis.carto.*;
import com.esri.arcgis.system.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class EngineViewer extends JFrame {
    // UI Components
    private JPanel contentPane;
    private IMapControlDefault mapControl;
    // ArcGIS Engine components
    private AoInitialize aoInitialize = null;
    public EngineViewer() {
        // 1. Initialize the JFrame
        setTitle("Java ArcGIS Engine Viewer");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 800, 600);
        // 2. Create the main content pane
        contentPane = new JPanel();
        contentPane.setLayout(new BorderLayout(0, 0));
        setContentPane(contentPane);
        // 3. Create the MapControl and add it to the frame
        mapControl = new MapControl();
        contentPane.add(mapControl, BorderLayout.CENTER);
        // 4. Add a menu bar with a "Load Map" option
        JMenuBar menuBar = new JMenuBar();
        JMenu fileMenu = new JMenu("File");
        JMenuItem loadMapItem = new JMenuItem("Load Map");
        loadMapItem.addActionListener(e -> loadMapDocument());
        fileMenu.add(loadMapItem);
        menuBar.add(fileMenu);
        setJMenuBar(menuBar);
    }
    /**
     * Initializes ArcGIS Engine licensing.
     * This MUST be called before using any other Engine functionality.
     * @return true if initialization was successful, false otherwise.
     */
    private boolean initializeEngine() {
        try {
            aoInitialize = new AoInitialize();
            // esriLicenseProductCode.esriLicenseProductCodeEngine is the standard for Engine apps
            // esriLicenseStatus.esriLicenseCheckedOut means the license was successfully acquired
            return aoInitialize.initialize(esriLicenseProductCode.esriLicenseProductCodeEngine) == esriLicenseStatus.esriLicenseCheckedOut;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
    /**
     * Loads a map document (.mxd) into the map control.
     */
    private void loadMapDocument() {
        // Path to your .mxd file
        String mapPath = "C:\\Data\\MyMap.mxd";
        try {
            // Create a MapDocument object
            IMapDocument mapDoc = new MapDocument();
            // Load the document from the file path
            mapDoc.open(mapPath, "");
            // Get the map from the document (an .mxd can have multiple data frames, we'll use the first one)
            IMap map = mapDoc.getMap(0);
            // Set the map of the map control
            mapControl.setMap(map);
            // IMPORTANT: Release the COM object to prevent memory leaks
            // This is crucial in Java/Engine applications
            com.esri.arcgis.system.AoUninitialize.releaseCOMObject(mapDoc);
            com.esri.arcgis.system.AoUninitialize.releaseCOMObject(map);
        } catch (Exception e) {
            JOptionPane.showMessageDialog(this, "Failed to load map document: " + e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
            e.printStackTrace();
        }
    }
    /**
     * The main method to run the application.
     */
    public static void main(String[] args) {
        // Use SwingUtilities to ensure the UI is created on the Event Dispatch Thread
        SwingUtilities.invokeLater(() -> {
            EngineViewer viewer = new EngineViewer();
            // Initialize ArcGIS Engine
            if (viewer.initializeEngine()) {
                viewer.setVisible(true);
            } else {
                JOptionPane.showMessageDialog(null, "Failed to initialize ArcGIS Engine. Please ensure the Engine Runtime is installed and licensed.", "License Error", JOptionPane.ERROR_MESSAGE);
                System.exit(1);
            }
        });
    }
    // Clean up COM objects when the frame is closed
    @Override
    public void dispose() {
        if (aoInitialize != null) {
            try {
                aoInitialize.shutdown();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        super.dispose();
    }
}

Step 3: Run the Application

  1. Make sure your MyMap.mxd file is at the specified path (C:\Data\MyMap.mxd).
  2. Run the main method in your EngineViewer class.
  3. A window should appear. Click File -> Load Map. Your map should be displayed in the window.

Best Practices and Important Considerations

  1. COM Object Management (Crucial!):

    • ArcGIS Engine is built on top of Component Object Model (COM), a Windows technology.
    • When you create a COM object (like MapDocument or FeatureClass), Java holds a "pointer" to it. The Java Garbage Collector will not automatically release the underlying COM object.
    • You must explicitly release these objects when you are done with them to prevent memory leaks and application instability.
    • Use com.esri.arcgis.system.AoUninitialize.releaseCOMObject(yourObject) to release them. The try-with-resources pattern is not directly applicable here, so you must do it manually in finally blocks or after use.
  2. Licensing:

    • Always call AoInitialize.initialize() at the very beginning of your application.
    • Check the return value to ensure you successfully acquired a license.
    • Call AoInitialize.shutdown() when your application closes to release the license.
  3. Threading (EDT):

    • All UI updates (e.g., changing the map extent, adding layers) should be performed on the Event Dispatch Thread (EDT).
    • For long-running operations (like geoprocessing, data loading), use a SwingWorker or a separate thread to avoid freezing the UI. Never perform heavy tasks on the EDT.
  4. Error Handling:

    • ArcGIS Engine methods throw standard Java exceptions. Wrap your calls in try...catch blocks to handle potential errors gracefully (e.g., file not found, invalid license, corrupt data).
  5. Use the Help Documentation:

    • The ArcGIS Engine Java Developer Help (usually ArcGIS_Engine_Java_Help.chm) is your best friend. It contains detailed documentation for every class, method, and property. It's invaluable for learning how to perform specific tasks.
分享:
扫描分享到社交APP
上一篇
下一篇