杰瑞科技汇

Java如何开发ArcGIS应用?

Of course! Using Java with ArcGIS is a powerful combination, especially for creating robust, server-side, and enterprise-grade geospatial applications. It's primarily done through the ArcGIS API for Java and the ArcGIS Runtime for Java.

Java如何开发ArcGIS应用?-图1
(图片来源网络,侵删)

Here's a comprehensive guide covering the key aspects, from choosing the right API to practical examples.


Choosing the Right ArcGIS Java API

There are two main Java APIs from Esri, and it's crucial to understand the difference.

Feature ArcGIS Runtime for Java ArcGIS API for Java (Server)
Primary Purpose Client-Side Applications. Build desktop apps, mobile apps (Android), and server-side applications that render maps and perform analysis. Server-Side Applications. Build web services (like map services, geoprocessing services) and web applications that run on a server (e.g., with Spring Boot).
Deployment Deployed as a standalone application (desktop, mobile) or as a service inside a servlet container (like Tomcat). Deployed as a web application on a Java web server (Tomcat, Jetty, WebLogic).
Core Functionality Map display, feature querying, editing, geocoding, routing, analysis tools. Service publishing, handling web requests, managing resources, server-side geoprocessing.
UI Framework Swing (Desktop), JavaFX (Desktop/Mobile), Android Views. No UI framework. You build the web service interface (REST endpoints, etc.).
Analogy Like a "map engine" for your client. Like the "kitchen" in a restaurant, preparing dishes (geospatial data/services) for the waiters (web clients).

For most new Java developers wanting to build server-side logic, the ArcGIS API for Java (Server) is the most common choice. For building a desktop map viewer, you'd use the ArcGIS Runtime for Java.


ArcGIS API for Java (Server) - The Core for Developers

This is the workhorse for creating custom server-side geospatial services in Java. It's built on top of the Spring framework, making it highly effective for building RESTful web services.

Java如何开发ArcGIS应用?-图2
(图片来源网络,侵删)

Key Concepts

  • ArcGIS Annotation: The magic that turns a simple Java class into a fully functional ArcGIS REST resource.
  • @Resource: Defines a top-level resource, like a map service or geoprocessing service.
  • @Operation: Defines a specific method on a resource that can be called via a REST request (e.g., GET, POST).
  • @Param: Binds incoming HTTP parameters to your Java method arguments.
  • MapService: A fundamental class that represents a map and its layers (e.g., a map document from ArcMap/ArcPro).
  • Geoprocessor: A class used to execute geoprocessing tools (e.g., buffer, intersect, network analysis).

How to Get Started

  1. Prerequisites:

    • Java Development Kit (JDK) 8 or later.
    • An IDE (IntelliJ IDEA or Eclipse).
    • Apache Maven or Gradle for dependency management.
    • A Java web server like Apache Tomcat.
  2. Add Dependencies: In your pom.xml (Maven), add the necessary dependencies.

    <dependencies>
        <!-- ArcGIS API for Java -->
        <dependency>
            <groupId>com.esri.arcgis</groupId>
            <artifactId>arcgis-api-java</artifactId>
            <version>10.9.1</version> <!-- Use the latest version -->
        </dependency>
        <!-- Spring Web for REST capabilities -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <version>2.7.0</version> <!-- Use a compatible version -->
        </dependency>
    </dependencies>

Practical Code Examples

Let's build a simple web service that takes a point and returns the buffer around it.

Example 1: A Simple Buffer Service

This service will accept a point's coordinates and a buffer distance and return the geometry of the buffer.

Java如何开发ArcGIS应用?-图3
(图片来源网络,侵删)
import com.esri.arcgis.server.arcobjectsoverhttp.ArcObjectsLocalServer;
import com.esri.arcgis.server.geoprocessing.GPUtilities;
import com.esri.arcgis.server.geoprocessing.Geoprocessor;
import com.esri.arcgis.spatialservices.Buffer;
import com.esri.arcgis.system.AoInitialize;
import com.esri.arcgis.system.EngineInitializer;
import com.esri.arcgis.system.PropertySet;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.*;
// 1. Define the Spring Boot Application
@SpringBootApplication
public class GeoprocessingServiceApplication {
    public static void main(String[] args) {
        // 2. Initialize ArcGIS Engine and Geoprocessing
        EngineInitializer.initializeEngine();
        AoInitialize aoInit = new AoInitialize();
        aoInit.initialize(esriLicenseProductCode.esriLicenseProductCodeArcInfo);
        SpringApplication.run(GeoprocessingServiceApplication.class, args);
    }
}
// 3. Create the REST Resource
@RestController
@RequestMapping("/gp")
public class BufferServiceResource {
    // 4. Define the Geoprocessing Operation
    @Operation(name = "bufferPoint", title = "Buffer a Point")
    public String bufferPoint(
            @Param(name = "input_point", title = "Input Point", required = true) String inputPointJson,
            @Param(name = "buffer_distance", title = "Buffer Distance", required = true) double bufferDistance) {
        try {
            // In a real application, you would load a proper GP service from a toolbox.
            // For this example, we'll use a simplified Buffer class.
            // A real implementation would look like this:
            // Geoprocessor gp = new Geoprocessor("http://yourserver/arcgis/services/YourToolbox/GPServer/Buffer");
            // GPUtilities.execute(gp, ...);
            // Simplified logic for demonstration
            System.out.println("Buffering point: " + inputPointJson + " by distance: " + bufferDistance);
            // Here you would call the actual ArcGIS Geoprocessing tool
            // and return the result as GeoJSON or JSON.
            // For now, we'll just return a success message.
            return "{\"status\": \"success\", \"message\": \"Buffer operation complete.\"}";
        } catch (Exception e) {
            e.printStackTrace();
            return "{\"status\": \"error\", \"message\": \"An error occurred: " + e.getMessage() + "\"}";
        }
    }
}

Example 2: A Map Service Query

This service will query a feature layer and return features that match a certain criteria.

import com.esri.arcgis.server.arcobjectsoverhttp.ArcObjectsLocalServer;
import com.esri.arcgis.mapping.MapService;
import com.esri.arcgis.server.MapServer;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/map")
public class MapServiceResource {
    // Assume a map service is running locally or accessible via a URL
    private final String MAP_SERVICE_URL = "http://sampleserver6.arcgisonline.com/arcgis/rest/services/Census/MapServer";
    @Operation(name = "queryFeatures", title = "Query Features")
    public String queryFeatures(
            @Param(name = "layer_id", title = "Layer ID", required = true) int layerId,
            @Param(name = "where_clause", title = "Where Clause", required = true) String whereClause) {
        try {
            // Connect to the map service
            MapServer mapServer = new MapServer(MAP_SERVICE_URL);
            // Perform a query
            // QueryFilter is a class that defines the query parameters
            com.esri.arcgis.server.QueryFilter queryFilter = new com.esri.arcgis.server.QueryFilter();
            queryFilter.setWhere(whereClause);
            // Execute the query
            com.esri.arcgis.server.RecordSet recordSet = mapServer.query(layerId, queryFilter, false);
            // Convert the result to JSON or another format
            // This is a simplified representation. You'd use a serializer.
            return "{\"status\": \"success\", \"feature_count\": " + recordSet.getRows().length + "}";
        } catch (Exception e) {
            e.printStackTrace();
            return "{\"status\": \"error\", \"message\": \"Query failed: " + e.getMessage() + "\"}";
        }
    }
}

Integration with ArcGIS Enterprise / ArcGIS Online

Your Java services don't exist in a vacuum. You typically integrate them into an ArcGIS Enterprise architecture.

  • As a Standalone Service: Deploy your Java app to Tomcat. It will have its own REST endpoint (e.g., http://myserver:8080/myjavaapp/gp/bufferPoint).
  • As a Geoprocessing Service: You can wrap your Java logic and publish it directly as a Geoprocessing service in ArcGIS Server. This is the most common and powerful approach. Your Java code becomes the "tool" that the server executes.
  • Consuming ArcGIS Online/Portal Services: Your Java application can act as a client. Use the ArcGIS API for Java to consume services from ArcGIS Online or your own portal.
    • Example: Fetch a web map from ArcGIS Online and display it in a JavaFX desktop application using the ArcGIS Runtime for Java.

Key Learning Resources

  1. Esri Developer Website (The Best Place to Start):

  2. GitHub:

  3. Books:

    • ArcGIS Server: Java Platform for Developers by Amir H. Behzadan (a bit older but covers fundamentals well).

Summary and Best Practices

  • Start with the API for Java (Server) if your goal is to build web services or backend logic.
  • Use Maven/Gradle to manage dependencies; it's much easier than manual JAR management.
  • Leverage Annotations: @Resource, @Operation, and @Param are what make the framework so powerful. Learn them well.
  • Separate Concerns: Keep your ArcGIS-specific logic separate from your general business logic. This makes your code more testable and maintainable.
  • Handle Errors Gracefully: Always wrap your ArcGIS calls in try-catch blocks and return meaningful error messages to the client.
  • Think REST: Design your services to be stateless and follow RESTful principles. Use HTTP methods (GET, POST) appropriately.
分享:
扫描分享到社交APP
上一篇
下一篇